mod clients;
mod environment;
mod mcp;
mod output;
mod trees;
mod types;
pub use trees::TreeCommand;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use clap::{Args, Parser, Subcommand, ValueEnum};
use getrandom::SysRng;
use getrandom::rand_core::UnwrapErr;
use nibkeep_base::{EntityId, SpaceId};
use nibkeep_crypto::RecoveryCode;
use nibkeep_model::{FieldName, Languages, ParseLanguagesError, Tag, TypeName};
use nibkeep_node::{
Backup, BackupEdit, DeviceRole, Kept, MoveHistory, MoveSecrets, Needs, NewBackup, NewRule,
Place, PolicyEdit, at_login,
};
use nibkeep_node::{Checkout, Dating, Edit, EntityView, LanguagesFor, NewLibrary};
use nibkeep_node::{
Holding, KeysError, Library, MemberRole, NewProtection, NodeError, PairingCode, Protection,
Replica, Role, SecretsState, Unlocker,
};
use nibkeep_std::{FILE, PHOTO, VIDEO};
use nibkeep_time::{Day, Edtf};
pub use environment::{
Account, Environment, Firewall, System, clear_git_variables, platform_keystore,
};
pub use mcp::McpServer;
use nibkeep_node::pointer::{
self, Found, LIBRARY_DATA, PointerError, holds_library,
resolved_as_far_as_it_exists as resolved,
};
use nibkeep_node::KEYSTORE_SERVICE;
const APP: &str = "nib";
impl From<PointerError> for CliError {
fn from(error: PointerError) -> Self {
match error {
PointerError::Bad { file, why } => Self::BadPointer { file, why },
PointerError::Stray { file, library } => Self::StrayPointer { file, library },
PointerError::InTheWay(file) => Self::PointerInTheWay(file),
PointerError::NotWritten { file, error } => Self::PointerNotWritten { file, error },
PointerError::NotTakenAway { file, error } => Self::PointerNotTakenAway { file, error },
PointerError::Library(error) => error.into(),
}
}
}
#[derive(Debug, Parser)]
#[command(name = "nib", bin_name = "nib", version = env!("NIB_VERSION"), about)]
pub struct Cli {
#[arg(long, global = true, value_name = "FOLDER")]
pub library: Option<PathBuf>,
#[arg(long, global = true, value_name = "SPACE")]
pub space: Option<String>,
#[arg(long, global = true)]
pub json: bool,
#[arg(long, global = true, hide = true)]
pub timings: bool,
#[arg(
long,
global = true,
value_name = "FILE",
env = "NIBKEEP_PASSPHRASE_FILE"
)]
pub passphrase_file: Option<PathBuf>,
#[command(subcommand)]
pub command: Command,
}
impl Cli {
fn network(&self, accept: bool) -> nibkeep_node::NetworkOptions {
let port = match &self.command {
Command::Sync { port, .. } if accept => *port,
Command::Device {
command: DeviceCommand::Pair { port, .. },
}
| Command::Space {
command: SpaceCommand::Invite { port, .. },
} if accept => port.port,
_ => 0,
};
nibkeep_node::NetworkOptions {
discovery: true,
port: (port != 0).then_some(port),
accept,
}
}
}
#[derive(Debug, Args)]
pub struct Port {
#[arg(
long,
value_name = "PORT",
env = "NIBKEEP_PORT",
default_value_t = nibkeep_node::DEFAULT_PORT
)]
pub port: u16,
}
const OVERVIEW: &[(&str, &[&str])] = &[
(
"Library",
&[
"init",
"status",
"verify",
"languages",
"protect",
"export",
"import",
],
),
(
"Entities",
&[
"new", "show", "edit", "list", "find", "history", "merge", "move", "purge", "type",
],
),
(
"Trees",
&[
"commit", "mv", "rm", "log", "diff", "blame", "restore", "revert", "update", "pull",
"clone",
],
),
("Files and secrets", &["file", "policy", "secret"]),
("Devices and sharing", &["sync", "device", "space", "mcp"]),
("Safekeeping", &["backup", "recovery", "purges"]),
];
#[must_use]
pub fn command() -> clap::Command {
use clap::CommandFactory;
use std::fmt::Write as _;
let command = Cli::command();
let styles = command.get_styles();
let (header, literal) = (styles.get_header(), styles.get_literal());
let width = OVERVIEW
.iter()
.flat_map(|(_, names)| names.iter())
.map(|name| name.len())
.max()
.unwrap_or(0);
let mut overview = String::new();
let mut aliases = Vec::new();
for (heading, names) in OVERVIEW {
let _ = writeln!(overview, "{header}{heading}:{header:#}");
for name in *names {
let about = command
.find_subcommand(name)
.and_then(clap::Command::get_about)
.map_or_else(String::new, ToString::to_string);
let _ = writeln!(overview, " {literal}{name:width$}{literal:#} {about}");
if let Some(sub) = command.find_subcommand(name) {
aliases.extend(
sub.get_visible_aliases()
.map(|alias| format!("{alias} for {name}")),
);
}
}
overview.push('\n');
}
if !aliases.is_empty() {
let last = aliases.len() - 1;
let words =
"Other names, as other version control systems have them:"
.split(' ')
.map(str::to_owned)
.chain(aliases.iter().enumerate().map(|(index, alias)| {
format!("{alias}{}", if index == last { "." } else { "," })
}));
let mut line = String::new();
for word in words {
if !line.is_empty() && line.len() + 1 + word.len() > 80 {
overview.push_str(&line);
overview.push('\n');
line.clear();
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(&word);
}
overview.push_str(&line);
overview.push('\n');
}
overview.push_str("nib help COMMAND, or nib COMMAND --help, tells more of each.\n\n");
let template = format!(
"{{before-help}}{{about-with-newline}}\n{{usage-heading}} {{usage}}\n\n{overview}{header}Options:{header:#}\n{{options}}{{after-help}}"
);
command.help_template(template)
}
fn clock<E: Environment>(environment: &E) -> impl Fn() -> u64 + use<E> {
let system = || {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| {
i128::try_from(since.as_millis()).unwrap_or(i128::MAX)
})
};
let offset = i128::from(environment.now()) - system();
move || u64::try_from(system() + offset).unwrap_or(0)
}
#[derive(Debug, Subcommand)]
pub enum Command {
#[command(group(
clap::ArgGroup::new("making")
.args(["name", "join", "device", "passphrase", "languages", "allow_fat"])
.multiple(true)
))]
Init {
#[arg(conflicts_with = "making")]
folder: Option<PathBuf>,
#[arg(short, long, conflicts_with = "making")]
message: Option<String>,
#[arg(long, conflicts_with = "making")]
yes: bool,
#[arg(long)]
name: Option<String>,
#[arg(long)]
device: Option<String>,
#[arg(long)]
passphrase: bool,
#[arg(
long,
value_name = "RANGES",
value_parser = parse_languages,
conflicts_with = "join"
)]
languages: Option<Languages>,
#[arg(long, value_name = "CODE", value_parser = parse_code, conflicts_with = "name")]
join: Option<PairingCode>,
#[arg(long, requires = "join", conflicts_with = "name")]
secrets: bool,
#[arg(long)]
allow_fat: bool,
},
Languages {
#[arg(value_name = "RANGES")]
ranges: Option<String>,
#[arg(long, conflicts_with = "app")]
device: bool,
#[arg(long)]
app: bool,
#[arg(long, conflicts_with = "ranges")]
clear: bool,
},
#[command(visible_alias = "st")]
Status {
#[arg(long)]
library_wide: bool,
#[arg(long, conflicts_with = "library_wide")]
secrets: bool,
},
Verify {
#[arg(long, value_name = "FOLDER")]
export: Option<PathBuf>,
#[arg(long, conflicts_with = "export")]
drive_checked: bool,
},
New {
#[arg(value_name = "TYPES")]
kind: String,
values: Vec<String>,
#[arg(long, value_name = "TAG", value_parser = parse_tag)]
language: Option<Tag>,
},
Show {
entity: String,
#[arg(long, value_name = "DAY", value_parser = parse_day)]
on: Option<Day>,
#[arg(long, value_name = "WHEN", value_parser = parse_moment)]
as_of: Option<Moment>,
},
Move {
entity: String,
#[arg(long, value_name = "SPACE")]
to: String,
#[arg(long)]
without_history: bool,
#[arg(long)]
keep_behind: bool,
#[arg(long)]
leave_secrets: bool,
#[arg(long)]
yes: bool,
},
Merge {
entity: String,
#[arg(required_unless_present = "undo")]
other: Option<String>,
#[arg(long)]
undo: bool,
},
Export {
folder: PathBuf,
#[arg(long)]
current: bool,
},
Import {
#[arg(required = true, value_name = "PATH")]
paths: Vec<PathBuf>,
#[arg(long, value_name = "SOURCE")]
from: Option<String>,
},
History {
entity: String,
field: Option<String>,
},
Edit(EditArgs),
Purge {
#[arg(required_unless_present = "behind")]
entity: Option<String>,
#[arg(required_unless_present = "behind")]
value: Option<String>,
#[arg(long, conflicts_with = "value")]
behind: bool,
#[arg(long)]
yes: bool,
},
Find {
#[arg(required = true)]
words: Vec<String>,
#[arg(long)]
all: bool,
},
List {
#[arg(value_name = "TYPE")]
kind: Option<String>,
#[arg(long = "where", value_name = "FIELD=VALUE")]
conditions: Vec<String>,
#[arg(long, value_name = "FIELD")]
sort: Option<String>,
#[arg(long, value_name = "DAY", value_parser = parse_day)]
on: Option<Day>,
},
Type {
#[command(subcommand)]
command: TypeCommand,
},
File {
#[command(subcommand)]
command: FileCommand,
},
#[command(flatten)]
Trees(TreeCommand),
Protect {
#[arg(long)]
passphrase: bool,
#[arg(long)]
secrets: bool,
},
Secret {
#[command(subcommand)]
command: SecretCommand,
},
Policy {
#[command(subcommand)]
command: PolicyCommand,
},
Space {
#[command(subcommand)]
command: SpaceCommand,
},
Device {
#[command(subcommand)]
command: DeviceCommand,
},
Backup {
#[command(subcommand)]
command: BackupCommand,
},
Recovery {
#[command(subcommand)]
command: RecoveryCommand,
},
Purges {
#[command(subcommand)]
command: Option<PurgesCommand>,
},
#[command(visible_alias = "push")]
Sync {
#[arg(long, conflicts_with = "wait")]
serve: bool,
#[arg(long, value_name = "SECONDS", default_value_t = 10)]
wait: u64,
#[arg(long, value_name = "SWITCH", conflicts_with_all = ["serve", "wait"])]
at_login: Option<Switch>,
#[arg(
long,
value_name = "PORT",
env = "NIBKEEP_PORT",
default_value_t = nibkeep_node::DEFAULT_PORT
)]
port: u16,
},
Pull {
#[arg(long, value_name = "SECONDS", default_value_t = 10)]
wait: u64,
#[arg(long)]
partial: bool,
#[arg(long, conflicts_with = "no_clone")]
clone: bool,
#[arg(long)]
no_clone: bool,
},
#[command(subcommand_required = true, arg_required_else_help = true)]
Mcp {
#[command(subcommand)]
action: McpAction,
},
#[command(flatten)]
Absent(Absent),
}
#[derive(Debug, Subcommand)]
pub enum McpAction {
Serve {
#[arg(long, value_name = "NAME")]
agent: Option<String>,
#[arg(long, value_name = "SECONDS", default_value_t = 2)]
wait: u64,
},
Enable {
#[arg(long, value_name = "CLIENT", conflicts_with = "print")]
client: Option<String>,
#[arg(long)]
print: bool,
},
Disable {
#[arg(long, value_name = "CLIENT")]
client: Option<String>,
},
}
#[derive(Debug, Subcommand)]
pub enum Absent {
#[command(hide = true)]
Add(Rest),
#[command(hide = true)]
Checkout(Rest),
#[command(hide = true)]
Branch(Rest),
#[command(hide = true)]
Tag(Rest),
#[command(hide = true)]
Stash(Rest),
#[command(hide = true)]
Reset(Rest),
#[command(hide = true)]
Rebase(Rest),
#[command(hide = true)]
Fetch(Rest),
}
impl Absent {
const fn instead(&self) -> (&'static str, &'static str) {
const NO_BRANCHES: &str = "a tree has no branches or tags: what devices change apart competes, and nib update merges it";
match self {
Self::Add(_) => (
"add",
"nib commit takes in new files, and leaves out what .nibignore names",
),
Self::Checkout(_) => (
"checkout",
"nib clone writes a tree into a folder, and nib restore writes a file as it was",
),
Self::Branch(_) => ("branch", NO_BRANCHES),
Self::Tag(_) => ("tag", NO_BRANCHES),
Self::Rebase(_) => ("rebase", NO_BRANCHES),
Self::Stash(_) => (
"stash",
"a tree has no stash: nib restore writes a file as it was, and keeps your edits beside it",
),
Self::Reset(_) => (
"reset",
"nib restore writes a file as it was, and nib revert undoes a revision",
),
Self::Fetch(_) => (
"fetch",
"nib sync brings what your other devices recorded without writing it, and nib pull writes it too",
),
}
}
}
#[derive(Debug, Args)]
pub struct Rest {
#[arg(trailing_var_arg = true, allow_hyphen_values = true, hide = true)]
rest: Vec<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum Switch {
On,
Off,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum NewSpacesArg {
Take,
Ask,
}
#[derive(Debug, Subcommand)]
pub enum SpaceCommand {
New {
name: String,
#[arg(long)]
group: bool,
#[arg(long = "on", value_name = "DEVICE")]
on: Vec<String>,
},
AddGroup {
space: String,
group: String,
#[arg(long, value_enum, default_value_t = RoleArg::Editor)]
role: RoleArg,
},
RemoveGroup {
space: String,
group: String,
},
Agree {
group: String,
space: String,
},
Withdraw {
group: String,
space: String,
},
List,
Take {
#[arg(value_name = "SPACE")]
wanted: String,
},
Drop {
#[arg(value_name = "SPACE")]
wanted: String,
},
Allow {
space: String,
device: String,
},
Show {
space: String,
},
Rename {
space: String,
name: String,
},
Invite {
space: String,
#[arg(long, value_enum, default_value_t = RoleArg::Editor)]
role: RoleArg,
#[arg(long = "as", value_name = "PERSON")]
person: Option<String>,
#[arg(long)]
yes: bool,
#[command(flatten)]
port: Port,
},
Join {
code: PairingCode,
#[arg(long)]
yes: bool,
#[arg(long = "on", value_name = "DEVICE")]
on: Vec<String>,
},
AiAgents {
space: String,
#[arg(value_enum)]
switch: Option<Switch>,
},
Link {
space: String,
member: String,
person: Option<String>,
},
Leave {
space: String,
#[arg(long)]
yes: bool,
},
Remove {
space: String,
member: String,
#[arg(long)]
yes: bool,
},
LetIn {
space: String,
member: String,
},
MakeDirect {
space: String,
member: String,
#[arg(long, value_enum, default_value_t = RoleArg::Editor)]
role: RoleArg,
},
Confirm {
space: String,
},
Claim {
space: String,
#[arg(long)]
yes: bool,
},
Reject {
space: String,
member: String,
},
Accept {
space: String,
member: String,
#[arg(long)]
yes: bool,
},
Role {
space: String,
member: String,
#[arg(value_enum)]
role: RoleArg,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum RoleArg {
Viewer,
Editor,
Admin,
}
impl RoleArg {
const fn role(self) -> MemberRole {
match self {
Self::Viewer => MemberRole::Viewer,
Self::Editor => MemberRole::Editor,
Self::Admin => MemberRole::Admin,
}
}
}
#[derive(Debug, Subcommand)]
pub enum PurgesCommand {
Stop {
purge: String,
#[arg(long, value_name = "BACKUP")]
on: Option<String>,
#[arg(long)]
yes: bool,
},
End {
purge: String,
#[arg(long, value_name = "BACKUP")]
on: Option<String>,
#[arg(long)]
yes: bool,
},
}
#[derive(Debug, Subcommand)]
pub enum RecoveryCommand {
New {
#[arg(long)]
secrets: bool,
#[arg(long)]
revoke_older: bool,
},
Confirm {
#[arg(long)]
secrets: bool,
#[arg(long)]
revoke_older: bool,
},
List,
Check {
#[arg(long)]
secrets: bool,
},
Revoke {
code: String,
#[arg(long)]
yes: bool,
},
Restore {
#[arg(value_name = "SOURCE")]
source: Option<PathBuf>,
#[arg(long, value_name = "DEVICE")]
keep: Vec<String>,
#[command(flatten)]
new: NewDevice,
},
FromCopy {
#[command(flatten)]
new: NewDevice,
},
}
#[derive(Debug, Args)]
pub struct NewDevice {
#[arg(long)]
pub device: Option<String>,
#[arg(long)]
pub passphrase: bool,
#[arg(long)]
pub allow_fat: bool,
}
#[derive(Debug, Subcommand)]
pub enum BackupCommand {
New {
folder: PathBuf,
#[arg(long)]
name: Option<String>,
#[arg(long = "of", value_name = "SPACE")]
spaces: Vec<String>,
#[arg(long = "policy", value_name = "POLICY")]
policies: Vec<String>,
#[arg(long)]
away: bool,
#[arg(long, value_name = "DAYS", value_parser = parse_waits)]
waits: Option<Waits>,
},
List,
Update {
backup: Option<String>,
#[arg(long, value_name = "FOLDER")]
at: Option<PathBuf>,
},
Edit {
backup: String,
#[arg(long)]
name: Option<String>,
#[arg(long = "of", value_name = "SPACE")]
spaces: Vec<String>,
#[arg(
long = "policy",
value_name = "POLICY",
conflicts_with = "every_policy"
)]
policies: Vec<String>,
#[arg(long)]
every_policy: bool,
#[arg(long, conflicts_with = "home")]
away: bool,
#[arg(long)]
home: bool,
#[arg(long, value_name = "DAYS", value_parser = parse_waits)]
waits: Option<Waits>,
},
Remove {
backup: String,
},
}
#[derive(Debug, Subcommand)]
pub enum DeviceCommand {
Pair {
#[arg(long, value_name = "NAME")]
ai_agent: Option<String>,
#[arg(long, conflicts_with = "ai_agent")]
phone: bool,
#[arg(long = "in", value_name = "SPACE")]
spaces: Vec<String>,
#[arg(long, conflicts_with = "ai_agent")]
give_secrets: bool,
#[command(flatten)]
port: Port,
},
List,
Revoke {
device: String,
#[arg(long)]
yes: bool,
#[arg(long)]
codes: bool,
},
Mark {
device: String,
#[arg(long, conflicts_with = "everyday")]
archive: bool,
#[arg(long)]
everyday: bool,
#[arg(long, conflicts_with = "home")]
away: bool,
#[arg(long)]
home: bool,
#[arg(long, value_name = "SIZE", value_parser = parse_keeps)]
keeps: Option<Keeps>,
#[arg(long, value_name = "DAYS", value_parser = parse_waits)]
waits: Option<Waits>,
#[arg(long, value_enum, value_name = "take|ask")]
new_spaces: Option<NewSpacesArg>,
},
Review,
Accept {
device: String,
#[arg(long)]
yes: bool,
},
}
#[derive(Debug, Args)]
pub struct EditArgs {
entity: String,
#[arg(required_unless_present_any = ["delete", "restore"])]
changes: Vec<String>,
#[arg(long, value_name = "DATE", value_parser = parse_edtf)]
date: Option<Edtf>,
#[arg(long, value_name = "DAY", value_parser = parse_day)]
on: Option<Day>,
#[arg(long, conflicts_with = "restore")]
delete: bool,
#[arg(long)]
restore: bool,
#[arg(long, value_name = "TAG", value_parser = parse_tag)]
language: Option<Tag>,
#[arg(long, conflicts_with = "form_of")]
form: bool,
#[arg(long, value_name = "VALUE")]
form_of: Option<String>,
}
#[derive(Clone, Copy, Debug)]
enum Forms<'a> {
No,
OfTheOnly,
Of(&'a str),
}
#[derive(Debug, Subcommand)]
pub enum TypeCommand {
Add {
name: String,
fields: Vec<String>,
},
Show {
name: String,
},
List,
}
#[derive(Debug, Subcommand)]
pub enum FileCommand {
Add {
#[arg(required = true)]
paths: Vec<PathBuf>,
#[arg(long)]
secret: bool,
#[arg(long, value_name = "ENTITY", requires = "secret")]
to: Vec<String>,
#[arg(long, value_name = "SOURCE", conflicts_with = "secret")]
from: Option<String>,
},
Checkout {
file: String,
path: Option<PathBuf>,
},
Where {
file: String,
},
#[command(hide = true)]
Thumbnail {
file: String,
path: PathBuf,
},
Thumbnails,
Pin {
file: String,
#[arg(long)]
device: Option<String>,
},
Unpin {
file: String,
#[arg(long)]
device: Option<String>,
},
Checkin {
copy: String,
#[arg(long)]
keep: bool,
#[arg(long)]
force: bool,
},
}
#[derive(Debug, Subcommand)]
pub enum SecretCommand {
Set {
entity: String,
field: String,
#[arg(long)]
generate: bool,
#[command(flatten)]
recipe: RecipeArgs,
},
Copy {
entity: String,
field: String,
#[arg(long, value_name = "SECONDS", default_value_t = nibkeep_passwords::CLEAR_AFTER.as_secs())]
clear_after: u64,
},
Generate {
#[command(flatten)]
recipe: RecipeArgs,
},
Code {
entity: String,
field: Option<String>,
},
Show {
entity: String,
field: String,
},
History {
entity: String,
field: String,
},
Clear {
entity: String,
field: String,
},
Purge {
entity: String,
field: String,
#[arg(long)]
yes: bool,
},
Ask {
from: String,
},
Give {
device: String,
},
FromCopy,
Save {
file: String,
path: Option<PathBuf>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Args)]
#[expect(
clippy::struct_excessive_bools,
reason = "one flag for each kind of character, as nibkeep_passwords::Recipe has"
)]
pub struct RecipeArgs {
#[arg(long)]
pub length: Option<usize>,
#[arg(long)]
pub no_lowercase: bool,
#[arg(long)]
pub no_uppercase: bool,
#[arg(long)]
pub no_digits: bool,
#[arg(long)]
pub no_symbols: bool,
#[arg(long)]
pub unambiguous: bool,
}
impl RecipeArgs {
fn recipe(&self) -> nibkeep_passwords::Recipe {
let default = nibkeep_passwords::Recipe::default();
nibkeep_passwords::Recipe {
length: self.length.unwrap_or(default.length),
lowercase: !self.no_lowercase,
uppercase: !self.no_uppercase,
digits: !self.no_digits,
symbols: !self.no_symbols,
unambiguous: self.unambiguous,
}
}
fn given(&self) -> bool {
self.length.is_some()
|| self.no_lowercase
|| self.no_uppercase
|| self.no_digits
|| self.no_symbols
|| self.unambiguous
}
}
#[derive(Debug, Subcommand)]
pub enum PolicyCommand {
List,
Show {
policy: String,
},
New {
name: String,
#[arg(long, default_value_t = 1)]
copies: u32,
#[arg(long, default_value_t = 0)]
away: u32,
#[arg(long, default_value_t = 0)]
archived: u32,
#[arg(long)]
in_place: bool,
},
Edit {
policy: String,
#[arg(long)]
name: Option<String>,
#[arg(long)]
copies: Option<u32>,
#[arg(long)]
away: Option<u32>,
#[arg(long)]
archived: Option<u32>,
#[arg(long, conflicts_with = "store")]
in_place: bool,
#[arg(long)]
store: bool,
},
Remove {
policy: String,
},
Rule {
#[command(subcommand)]
command: RuleCommand,
},
Set {
entity: String,
#[arg(required_unless_present = "clear")]
policy: Option<String>,
#[arg(long, conflicts_with = "policy")]
clear: bool,
},
Why {
entity: String,
},
Check,
}
#[derive(Debug, Subcommand)]
pub enum RuleCommand {
New {
policy: String,
#[arg(long = "type", value_name = "TYPE")]
of_type: Option<String>,
#[arg(long, value_name = "FIELD")]
has: Option<String>,
#[arg(long, value_name = "FOLDER")]
folder: Option<PathBuf>,
#[arg(long, value_name = "TYPE")]
media_type: Option<String>,
#[arg(long, value_name = "SIZE", value_parser = parse_size)]
larger_than: Option<u64>,
#[arg(long, value_name = "SIZE", value_parser = parse_size)]
asks_above: Option<u64>,
#[command(flatten)]
place: PlaceArgs,
},
Remove {
rule: String,
},
Move {
rule: String,
#[command(flatten)]
place: PlaceArgs,
},
}
#[derive(Debug, Args)]
pub struct PlaceArgs {
#[arg(long, conflicts_with_all = ["last", "before", "after"])]
first: bool,
#[arg(long, conflicts_with_all = ["before", "after"])]
last: bool,
#[arg(long, value_name = "RULE", conflicts_with = "after")]
before: Option<String>,
#[arg(long, value_name = "RULE")]
after: Option<String>,
}
const LINKS_SHOWN: usize = 10;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CliError {
#[error("{0}")]
Import(String),
#[error(
"{0} has no thumbnail: the device that added it could not read its format, or it is no picture"
)]
NoThumbnail(String),
#[error("{} exists already", .0.display())]
Exists(PathBuf),
#[error(
"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"
)]
NotInLibrary,
#[error("there is no library in {}", .0.display())]
NoLibraryIn(PathBuf),
#[error(
"nib may not read {folder}: {error}; on a Mac, allow your terminal to reach removable volumes, in System Settings, Privacy & Security, Files and Folders",
folder = .0.display(),
error = .1
)]
NoAccess(PathBuf, #[source] io::Error),
#[error("there is no library in {}, which NIBKEEP_LIBRARY names", .0.display())]
NoDefaultLibrary(PathBuf),
#[error("NIBKEEP_LIBRARY names {}, which is not a full path", .0.display())]
RelativeDefault(PathBuf),
#[error(
"a library was started in {}, but not finished; remove that folder to start again",
.0.display()
)]
Unfinished(PathBuf),
#[error(
"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",
.0.display()
)]
IsCopy(PathBuf),
#[error("no secrets were taken from a copy")]
NoSecretsInCopies,
#[error("there is no copy of a library in {}", .0.display())]
NoCopy(PathBuf),
#[error("{} holds copies of several libraries' devices; keep the one to use", .0.display())]
SeveralCopies(PathBuf),
#[error(
"{} 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",
.0.display()
)]
CopiedHere(PathBuf),
#[error(
"{} 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",
.0.display()
)]
NoJournal(PathBuf),
#[error(
"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",
.0.display()
)]
UncleanRemoval(PathBuf),
#[error("{} is in a library's own folder .nib; start the library elsewhere", .0.display())]
InLibraryData(PathBuf),
#[error("the current folder cannot be found: {0}")]
NoCurrentFolder(#[source] io::Error),
#[error(transparent)]
Languages(#[from] ParseLanguagesError),
#[error("--form adds and removes forms with field+=value and field-=value; there are none")]
NoForms,
#[error("{entity} and {into} are one entity already")]
OneAlready {
entity: String,
into: String,
},
#[error("no entity was merged into {0}")]
NothingMerged(String),
#[error("say which entity to set apart from {entity}: {candidates}")]
WhichMerged {
entity: String,
candidates: String,
},
#[error("no entity merged into {entity} is {other}")]
NotMergedInto {
entity: String,
other: String,
},
#[error("the entity never had a field {0}")]
NoHistory(String),
#[error("the moment cannot be used: {0}")]
Moment(String),
#[error("the library had no record of {entity} by {when}")]
NotYet {
entity: String,
when: String,
},
#[error("the passphrases differ")]
PassphrasesDiffer,
#[error(
"{} was checked out from a version that is no longer the file's own; --force records its edits on top, and history keeps both",
.0.display()
)]
Stale(PathBuf),
#[error("{}", files_failed(*.0))]
FilesFailed(usize),
#[error(
"{name} is not on this device, and no device that holds it was found on the network: {}",
holders.join(", ")
)]
NotFetched {
name: String,
holders: Vec<String>,
},
#[error(
"{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",
holders.join(", ")
)]
NotGiven {
name: String,
holders: Vec<String>,
},
#[error("{}", syncs_failed(*.0))]
SyncsFailed(usize),
#[error("{0} did not sync in time; it may be busy with a long sync")]
NotAnswered(String),
#[error(
"AI agents are not allowed on this library here; allow them with nib mcp enable in its folder"
)]
NotAnAiAgent,
#[error(
"nib knows no AI client {0}; it knows Claude Code (claude) and Codex (codex), and --print gives the line for any other"
)]
UnknownAiClient(String),
#[error(
"nib mcp serve asks for nothing on a terminal; give the library's passphrase with --passphrase-file"
)]
NoTerminal,
#[error("the values differ")]
ValuesDiffer,
#[error("the value is empty")]
EmptyValue,
#[error(
"{0} is secret: nib secret set asks for its value without showing it, and nib secret clear clears it"
)]
SecretField(nibkeep_model::FieldName),
#[error(
"{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"
)]
SecretGiven(nibkeep_model::FieldName),
#[error("{0} is secret: nib secret history shows the values it has had")]
SecretHistory(nibkeep_model::FieldName),
#[error("{} is a folder; nib file add --secret adds files one by one", .0.display())]
SecretFolder(PathBuf),
#[error(
"{0} is a secret file, of which NibKeep records no copies; nib secret save writes one that nothing keeps track of"
)]
SecretFileCheckout(String),
#[error("{0} is not secret; nib show and nib edit read and set it")]
NotSecret(nibkeep_model::FieldName),
#[error(transparent)]
Generator(#[from] nibkeep_passwords::GeneratorError),
#[error(transparent)]
OneTime(#[from] nibkeep_passwords::OneTimeError),
#[error(transparent)]
Clipboard(#[from] nibkeep_passwords::ClipboardError),
#[error("--length and the --no- options say what --generate makes; give --generate too")]
RecipeWithoutGenerate,
#[error(
"{0} holds the secret of one-time codes, which the site gives; --generate makes passwords"
)]
GeneratedOneTimeCode(nibkeep_model::FieldName),
#[error("there is no rule {0}; nib policy list numbers the rules")]
NoRule(String),
#[error("say where the rule goes: --first, --last, --before RULE or --after RULE")]
WhereTo,
#[error("the library holds no secrets yet; nib secret set stores the first")]
NoSecrets,
#[error("{entity} has no value of {field}")]
NoSecretValue {
entity: String,
field: nibkeep_model::FieldName,
},
#[error("the passphrase is empty")]
EmptyPassphrase,
#[error("the passphrase file {} cannot be read: {error}", path.display())]
PassphraseFile {
path: PathBuf,
error: io::Error,
},
#[error("others can read the passphrase file {}; make it yours alone, such as with chmod 600", .0.display())]
PassphraseFileOpen(PathBuf),
#[error(
"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"
)]
AtLoginPassphrase,
#[error("there is no home folder here to keep the list of libraries synced from login in")]
NoStateFolder,
#[error(
"nibkeep-sync, which syncs from login, is not installed beside nib; cargo install --path apps/nib installs both"
)]
NoSyncProgram,
#[error("the library's keys are in the platform's keystore, which is not available")]
NoKeystore,
#[error("the platform's keystore failed ({0}); start the library with --passphrase instead")]
Keystore(NodeError),
#[error(
"there is no platform keystore here; nib protect --passphrase protects with a passphrase"
)]
NoKeystoreToProtect,
#[error(
"the platform's keystore failed ({0}); nib protect --passphrase protects with a passphrase"
)]
KeystoreToProtect(NodeError),
#[error("{0} is not a valid name")]
Name(String),
#[error(
"{name} is a standard name, which only the standard vocabulary gives; choose another \
{what} name, such as one starting with local."
)]
StandardName {
name: String,
what: &'static str,
},
#[error(
"a field is name:kind, with flags such as :many, :lww, :secret or :role after it, not {0}"
)]
Field(String),
#[error("there is no kind of value called {kind}; the kinds are {kinds}")]
Kind {
kind: String,
kinds: String,
},
#[error(
"there is no flag {0} for a field; the flags are many, lww, secret, role, stands-for, search-through, code, unit= and reverse="
)]
Flag(String),
#[error("{0}")]
Flags(String),
#[error("there is no type {0}; define it with nib type add")]
NoType(TypeName),
#[error("{name} could be any of the types {candidates}")]
AmbiguousType {
name: String,
candidates: String,
},
#[error(
"{types} has no field {field}; give its full name, such as local.{field}, for a field that no type defines"
)]
NoField {
field: String,
types: String,
},
#[error("{field} could be any of the fields {candidates}")]
AmbiguousField {
field: String,
candidates: String,
},
#[error("an entity's types are given with type+=TYPE and taken away with type-=TYPE")]
TypeSet,
#[error("a value is field=value, not {0}")]
Assignment(String),
#[error("{}", unsound(*.0))]
Unsound(usize),
#[error("{}", unsound_export(*.0))]
UnsoundExport(usize),
#[error("nothing was purged; add --yes to purge for good")]
Unconfirmed,
#[error("nothing was moved; add --yes to move them all")]
UnconfirmedMove,
#[error("no tree was started; add --yes to start it")]
UnconfirmedStart,
#[error("{} holds no Git repository with a commit to pin", .0.display())]
NoGitCommit(PathBuf),
#[error("{} is in no tree's folder on this device; nib init makes it one", .0.display())]
NotInTree(PathBuf),
#[error(
"{} is in no tree's folder on this device: name a tree with --tree, or see an entity's values with nib history",
.0.display()
)]
NoTreeHere(PathBuf),
#[error(
"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",
.0.display()
)]
NoLibraryForTree(PathBuf),
#[error("{} should name the library of the tree in its folder, but {why}", .file.display())]
BadPointer {
file: PathBuf,
why: String,
},
#[error(
"{} 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",
.file.display(),
.library.display()
)]
StrayPointer {
file: PathBuf,
library: PathBuf,
},
#[error(
"{} 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",
.0.display()
)]
ThroughPointer(PathBuf),
#[error(
"{} is no file: nib keeps a file there that names the library of a tree outside the library's folder",
.0.display()
)]
PointerInTheWay(PathBuf),
#[error(
"{} could not be written: {error}; the tree is there, and nib init {} in the library's folder writes the file again",
.file.display(),
pointer::folder_of(.file)
)]
PointerNotWritten {
file: PathBuf,
error: io::Error,
},
#[error(
"{} could not be deleted: {error}; the tree is there, and once the file is gone, commands in {} find the library",
.file.display(),
pointer::folder_of(.file)
)]
PointerNotTakenAway {
file: PathBuf,
error: io::Error,
},
#[error("the system names no account for you: give your name with nib init --name YOUR-NAME")]
NoAccountName,
#[error("there is no {verb} command: {instead}")]
NoSuchCommand {
verb: &'static str,
instead: &'static str,
},
#[error(
"{0} is no revision: nib revert undoes a revision, and nib restore {0} writes a file as it was"
)]
RevertTakesRevision(String),
#[error("nothing was revoked; add --yes to revoke for good")]
UnconfirmedRevoke,
#[error("only {0} says whether it takes new spaces: run nib device mark --new-spaces there")]
NewSpacesElsewhere(String),
#[error("that was no recovery code; nothing was changed")]
NotARecoveryCode,
#[error(
"the library here still unlocks with this computer's keystore: there is nothing to recover, and a recovery would only revoke it"
)]
StillUnlocks,
#[error("the library names no such recovery code")]
UnknownRecoveryCode,
#[error("nothing was accepted; add --yes to accept them")]
UnconfirmedAccept,
#[error("you did not leave; add --yes to leave")]
UnconfirmedLeave,
#[error("nobody was removed; add --yes to remove them")]
UnconfirmedRemove,
#[error("nothing was claimed; add --yes to claim the admin role")]
UnconfirmedClaim,
#[error(
"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"
)]
UnconfirmedInvite,
#[error("{0} is both set and cleared")]
SetAndCleared(nibkeep_model::FieldName),
#[error("{field} takes {expected}")]
Value {
field: nibkeep_model::FieldName,
expected: &'static str,
},
#[error(
"{reference} could be any of {count} entities; give the ID, or its start:\n{candidates}"
)]
Ambiguous {
reference: String,
count: usize,
candidates: String,
},
#[error(transparent)]
Node(#[from] NodeError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Timings {
pub waiting: Option<Duration>,
pub unlock: Option<Duration>,
pub open: Option<Duration>,
pub work: Duration,
pub print: Duration,
}
impl Timings {
fn parts(&self) -> Vec<(&'static str, Duration)> {
let mut parts = Vec::new();
for (name, part) in [
("waiting", self.waiting),
("unlock", self.unlock),
("open", self.open),
] {
if let Some(duration) = part {
parts.push((name, duration));
}
}
parts.push(("work", self.work));
parts.push(("print", self.print));
parts
}
#[must_use]
pub fn describe(&self, json: bool) -> String {
let parts = self.parts();
if json {
let object: serde_json::Map<String, serde_json::Value> = parts
.iter()
.map(|(part, duration)| (format!("{part}_seconds"), duration.as_secs_f64().into()))
.collect();
return serde_json::Value::Object(object).to_string();
}
parts
.iter()
.map(|(part, duration)| format!("{part} {:.3} s", duration.as_secs_f64()))
.collect::<Vec<_>>()
.join(", ")
}
fn before_work(&self) -> Duration {
[self.waiting, self.unlock, self.open]
.into_iter()
.flatten()
.sum()
}
}
fn add(part: &mut Option<Duration>, duration: Duration) {
*part = Some(part.unwrap_or_default() + duration);
}
pub fn run<E: Environment>(
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
run_command(cli, environment, output, &mut Timings::default())
}
pub fn run_timed<E: Environment>(
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<Timings, CliError> {
let started = Instant::now();
let mut timings = Timings::default();
let mut timed = Timed {
inner: output,
spent: Duration::ZERO,
};
run_command(cli, environment, &mut timed, &mut timings)?;
timed.flush()?;
timings.print = timed.spent;
timings.work = started
.elapsed()
.saturating_sub(timings.before_work() + timings.print);
Ok(timings)
}
#[must_use]
pub fn printable(line: &str) -> std::borrow::Cow<'_, str> {
fn hidden(c: char) -> bool {
(c.is_control() && c != '\n')
|| matches!(c, '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}')
}
if !line.chars().any(hidden) {
return line.into();
}
line.chars()
.map(|c| {
if hidden(c) {
c.escape_debug().to_string()
} else {
c.to_string()
}
})
.collect::<String>()
.into()
}
pub struct UntilUnread<W> {
inner: W,
unread: bool,
}
impl<W> UntilUnread<W> {
pub const fn new(inner: W) -> Self {
Self {
inner,
unread: false,
}
}
fn read_or_not<T>(&mut self, done: io::Result<T>, nothing: T) -> io::Result<T> {
match done {
Err(error) if error.kind() == io::ErrorKind::BrokenPipe => {
self.unread = true;
Ok(nothing)
}
done => done,
}
}
}
impl<W: Write> Write for UntilUnread<W> {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if self.unread {
return Ok(bytes.len());
}
let written = self.inner.write(bytes);
self.read_or_not(written, bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
if self.unread {
return Ok(());
}
let flushed = self.inner.flush();
self.read_or_not(flushed, ())
}
}
struct Timed<'a> {
inner: &'a mut dyn Write,
spent: Duration,
}
impl Write for Timed<'_> {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
let started = Instant::now();
let written = self.inner.write(bytes);
self.spent += started.elapsed();
written
}
fn flush(&mut self) -> io::Result<()> {
let started = Instant::now();
let flushed = self.inner.flush();
self.spent += started.elapsed();
flushed
}
}
fn run_command<E: Environment>(
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
timings: &mut Timings,
) -> Result<(), CliError> {
nibkeep_node::name_program(APP);
if let Command::Absent(absent) = &cli.command {
let (verb, instead) = absent.instead();
return Err(CliError::NoSuchCommand { verb, instead });
}
if let Command::Secret {
command: SecretCommand::Generate { recipe },
} = &cli.command
{
return generate_command(recipe, cli.json, environment, output);
}
let (found, making) = command_folder(cli, environment)?;
place_not_through_pointer(cli, &found)?;
let folder = found.folder.clone();
let directory = folder.join(LIBRARY_DATA);
if let Command::Mcp {
action: McpAction::Serve { .. },
} = &cli.command
{
return mcp::serve(cli, environment, output);
}
if making {
let library = new_library(&directory, cli, environment, timings, output)?;
let zone = environment.time_zone();
let checks = output::Checks {
status: None,
name_of: &|_, _| None,
zone: &zone,
};
let status = (
&library.status()?,
&[][..],
&std::collections::BTreeMap::new(),
);
return output::status(status, checks, &folder, cli.json, output);
}
if let Command::Verify {
drive_checked: true,
..
} = &cli.command
{
Library::drive_checked(&directory)?;
}
if let Command::Sync {
at_login: Some(switch),
..
} = &cli.command
{
return at_login_command(*switch, &directory, cli, environment, timings, output);
}
let opened = open(
&directory,
cli.passphrase_file.as_deref(),
environment,
timings,
);
let mut library = opened.map_err(|error| opened_error(error, &directory))?;
check_found(&library, &found, cli, environment)?;
if library.told_of_syncing()? {
environment.note(SYNCED_BY_PROGRAM);
}
if let Some(space) = &cli.space {
let space = library.find_space(space)?;
library.choose_space(Some(space))?;
}
if let Command::Sync { serve: true, .. } = &cli.command {
return serve_command(library, cli, environment, output);
}
if let Command::Secret {
command: SecretCommand::Copy {
entity,
field,
clear_after,
},
} = &cli.command
{
let board = environment.clipboard()?;
let read = read_secret(&mut library, entity, field, environment, timings)
.map_err(|error| candidates_named(&library, error, environment))?;
drop(library);
return copy_and_clear(board, &read, *clear_after, cli.json, environment, output);
}
let ran = match &cli.command {
Command::Backup { .. } | Command::Recovery { .. } => {
safekeeping_command(&mut library, cli, environment, timings, output)
}
Command::Purges { command } => purges_waiting_command(
&mut library,
command.as_ref(),
cli.json,
environment,
output,
),
_ => library_command(&mut library, cli, &folder, environment, timings, output),
};
ran.map_err(|error| candidates_named(&library, error, environment))
}
fn place_not_through_pointer(cli: &Cli, found: &Found) -> Result<(), CliError> {
let place = matches!(
&cli.command,
Command::Verify {
drive_checked: true,
..
} | Command::Sync {
at_login: Some(_),
..
}
);
match &found.named_in {
Some(file) if place => Err(CliError::ThroughPointer(file.clone())),
_ => Ok(()),
}
}
fn check_found<E: Environment>(
library: &Library,
found: &Found,
cli: &Cli,
environment: &E,
) -> Result<(), CliError> {
let starting = match &cli.command {
Command::Init { folder, .. } => Some(match folder {
Some(folder) => absolute(folder, environment)?,
None => current_dir(environment)?,
}),
_ => None,
};
Ok(pointer::check(library, found, starting.as_deref())?)
}
fn command_folder<E: Environment>(cli: &Cli, environment: &E) -> Result<(Found, bool), CliError> {
if cli.command.makes_library() {
return Ok((
Found::library(new_library_folder(cli.library.as_deref(), environment)?),
true,
));
}
if let Command::Init {
folder,
message,
yes,
..
} = &cli.command
{
let from = match folder {
Some(folder) => absolute(folder, environment)?,
None => current_dir(environment)?,
};
let here = environment.current_dir().ok();
let places: Vec<&Path> = std::iter::once(from.as_path())
.chain(here.as_deref())
.collect();
let given = cli.library.as_deref();
let alone = folder.is_none() && message.is_none() && !yes;
let found = match library_folder_from(given, &places, environment) {
Err(CliError::BadPointer { file, .. }) if file == from.join(LIBRARY_DATA) => {
library_folder_from(given, &places[1..], environment)
}
found => found,
};
return match found {
Ok(found) => Ok((found, false)),
Err(CliError::NotInLibrary | CliError::NoLibraryIn(_)) if alone => Ok((
Found::library(new_library_folder(given, environment)?),
true,
)),
Err(CliError::NotInLibrary) => Err(CliError::NoLibraryForTree(from)),
Err(error) => Err(error),
};
}
if let (
Command::Sync {
at_login: Some(Switch::Off),
..
},
Some(given),
) = (&cli.command, cli.library.as_deref())
{
return Ok((
Found::library(resolved(absolute(given, environment)?)),
false,
));
}
Ok((library_folder(cli.library.as_deref(), environment)?, false))
}
impl Command {
const fn is_of_trees(&self) -> bool {
matches!(
self,
Self::Init { .. } | Self::Status { .. } | Self::Trees(_) | Self::Pull { .. }
)
}
const fn makes_library(&self) -> bool {
matches!(
self,
Self::Init {
name,
join,
device,
passphrase,
languages,
allow_fat,
..
} if name.is_some()
|| join.is_some()
|| device.is_some()
|| *passphrase
|| languages.is_some()
|| *allow_fat
) || matches!(
self,
Self::Recovery {
command: RecoveryCommand::Restore { .. } | RecoveryCommand::FromCopy { .. }
}
)
}
}
fn library_folder<E: Environment>(
given: Option<&Path>,
environment: &E,
) -> Result<Found, CliError> {
if given.is_some() {
return library_folder_from(given, &[], environment);
}
library_folder_from(given, &[¤t_dir(environment)?], environment)
}
fn library_folder_from<E: Environment>(
given: Option<&Path>,
places: &[&Path],
environment: &E,
) -> Result<Found, CliError> {
if let Some(given) = given {
let folder = resolved(absolute(given, environment)?);
if !holds_library(&folder) {
return Err(match unreadable(&folder) {
Some(error) => CliError::NoAccess(folder, error),
None => CliError::NoLibraryIn(folder),
});
}
return Ok(Found::library(folder));
}
let ceiling = environment.ceiling();
for here in places {
if let Some(found) = pointer::nearest(here, ceiling.as_deref())? {
return Ok(found);
}
if let Some(error) = unreadable(here) {
return Err(CliError::NoAccess(here.to_path_buf(), error));
}
}
let named = environment
.default_library()
.ok_or(CliError::NotInLibrary)?;
if !named.is_absolute() {
return Err(CliError::RelativeDefault(named));
}
let named = resolved(named);
if !holds_library(&named) {
return Err(CliError::NoDefaultLibrary(named));
}
Ok(Found::library(named))
}
fn new_library_folder<E: Environment>(
given: Option<&Path>,
environment: &E,
) -> Result<PathBuf, CliError> {
let folder = match given {
Some(given) => absolute(given, environment)?,
None => current_dir(environment)?,
};
let folder = resolved(folder);
if folder
.components()
.any(|part| part.as_os_str() == LIBRARY_DATA)
{
return Err(CliError::InLibraryData(folder));
}
Ok(folder)
}
const 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.";
fn unfinished(directory: &Path) -> CliError {
CliError::Unfinished(
Library::replica_folder(directory).unwrap_or_else(|_| directory.to_owned()),
)
}
fn unreadable(folder: &Path) -> Option<io::Error> {
match std::fs::read_dir(folder) {
Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Some(error),
_ => None,
}
}
fn current_dir<E: Environment>(environment: &E) -> Result<PathBuf, CliError> {
environment.current_dir().map_err(CliError::NoCurrentFolder)
}
fn absolute<E: Environment>(folder: &Path, environment: &E) -> Result<PathBuf, CliError> {
if folder.is_absolute() {
Ok(folder.to_owned())
} else {
Ok(current_dir(environment)?.join(folder))
}
}
fn library_command<E: Environment>(
library: &mut Library,
cli: &Cli,
folder: &Path,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
match &cli.command {
Command::Languages { .. } => {
languages_command(library, &cli.command, json, environment, output)
}
Command::Show { .. }
| Command::History { .. }
| Command::Export { .. }
| Command::Find { .. }
| Command::List { .. } => reading_command(library, cli, folder, environment, output),
Command::Verify { export, .. } => {
verify_command(library, export.as_deref(), json, environment, output)
}
Command::New {
kind,
values,
language,
} => {
let new = (kind.as_str(), values.as_slice(), language.as_ref());
new_command(library, new, json, environment, output)
}
Command::Merge {
entity,
other,
undo,
} => {
let merge = (entity.as_str(), other.as_deref(), *undo);
merge_command(library, merge, json, environment, output)
}
Command::Edit(arguments) => edit_command(library, arguments, json, environment, output),
Command::Move {
entity,
to,
without_history,
keep_behind,
leave_secrets,
yes,
} => {
let args = (
(entity.as_str(), to.as_str(), *without_history, *yes),
(*keep_behind, *leave_secrets),
);
move_command(library, args, json, environment, timings, output)
}
Command::Purge { .. } => purge_or_list(library, cli, environment, timings, output),
Command::File { command } => {
let file = (command, folder);
file_command(library, file, cli, environment, timings, output)
}
Command::Policy { command } => policy_command(library, command, json, environment, output),
Command::Secret { command } => {
secret_command(library, command, json, environment, timings, output)
}
Command::Protect {
passphrase,
secrets,
} => {
let protect = (*passphrase, *secrets);
protect_command(library, protect, json, environment, timings, output)?;
if *passphrase && !*secrets {
turn_off_at_login(&folder.join(LIBRARY_DATA), environment);
}
Ok(())
}
Command::Import { paths, from } => {
let import = (paths.as_slice(), from.as_deref());
import_command(library, import, json, environment, output)
}
Command::Type { command } => type_command(library, command, json, environment, output),
Command::Space { command } => space_command(library, command, cli, environment, output),
Command::Device { command } => {
let directory = folder.join(LIBRARY_DATA);
device_command(
library,
(command, &directory),
cli,
environment,
timings,
output,
)
}
Command::Sync {
serve: false, wait, ..
} => {
let wait = Duration::from_secs(*wait);
sync_command(library, cli, wait, environment, output)
}
Command::Sync { serve: true, .. } => unreachable!("nib sync --serve closes the library"),
Command::Mcp {
action: McpAction::Serve { .. },
} => unreachable!("nib mcp serve opens the library itself"),
Command::Mcp { action } => mcp::manage(library, action, folder, cli, environment, output),
command if command.is_of_trees() => {
tree_command(library, cli, folder, environment, timings, output)
}
_ => unreachable!("run_command runs it"),
}
}
fn tree_command<E: Environment>(
library: &mut Library,
cli: &Cli,
folder: &Path,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
match &cli.command {
Command::Init {
folder: target,
message,
yes,
..
} => {
let start = (target.as_deref(), message.as_deref(), *yes);
trees::init_command(
library,
(folder, start),
json,
(environment, timings),
output,
)
}
Command::Status { secrets: true, .. } => {
trees::secrets_command(library, json, environment, output)
}
Command::Status { library_wide, .. } => {
if !*library_wide && trees::in_tree_here(library, environment)? {
return trees::status_command(library, json, environment, output);
}
reading_command(library, cli, folder, environment, output)
}
Command::Trees(command) => trees::tree_command(
library,
(folder, command),
json,
(environment, timings),
output,
),
Command::Pull {
wait,
partial,
clone,
no_clone,
} => {
let wait = Duration::from_secs(*wait);
let update = (*partial, *clone, *no_clone);
pull_command(library, cli, (wait, update), environment, timings, output)
}
_ => unreachable!("only the commands of trees come here"),
}
}
const PAIRING_MINUTES: u64 = 10;
const FIND_SPONSOR: Duration = Duration::from_mins(1);
fn pair_command<E: Environment>(
library: &mut Library,
((ai_agent, spaces, give_secrets), device): (
(Option<&str>, &[nibkeep_base::SpaceId], bool),
&nibkeep_node::NewDevice,
),
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
library.check_not_ai_agent("add devices")?;
if ai_agent.is_none() {
library.check_new_device(device)?;
}
if give_secrets {
unlock_secrets(library, false, environment, timings)?;
}
let _borrowed =
nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
let code = PairingCode::generate(environment.rng());
let network = library.network(cli.network(true))?;
output::port_taken(&network, json, output)?;
output::pairing_code(&code, PAIRING_MINUTES, json, output)?;
let now = clock(environment);
let printing = RefCell::new(output);
let wrong_try = |error: &NodeError, left: usize| {
let _ = output::wrong_try(error, left, json, &mut **printing.borrow_mut());
};
let showing = nibkeep_node::Showing {
timeout: Duration::from_mins(PAIRING_MINUTES),
wrong_try: &wrong_try,
};
let paired = match ai_agent {
Some(name) => nibkeep_node::pair_ai_agent_in(
library,
&network,
&code,
(name, spaces),
showing,
&now,
environment.rng(),
),
None => nibkeep_node::pair_device(
library,
&network,
&code,
(device, give_secrets),
showing,
&now,
environment.rng(),
),
};
library.lock_secrets();
output::paired(&paired?, json, printing.into_inner())
}
fn device_command<E: Environment>(
library: &mut Library,
(command, directory): (&DeviceCommand, &Path),
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
match command {
DeviceCommand::List => {
let records = library.sync_records(UnwrapErr(SysRng)).ok();
let recorded = records.as_ref().and_then(|records| records.replicas().ok());
let holder = records.and_then(|records| records.holder().ok().flatten());
let zone = environment.time_zone();
let synced = (holder.as_ref(), recorded.as_ref());
let replicas = library.replicas()?;
let this = replicas
.iter()
.find(|replica| replica.this)
.map(|replica| replica.id);
let at_login = at_login_state((directory, this), environment);
let shown = (synced, at_login.as_ref());
output::replicas(&replicas, shown, &zone, cli.json, output)
}
DeviceCommand::Pair {
ai_agent,
phone,
spaces,
give_secrets,
..
} => {
let mut chosen = Vec::new();
for space in spaces {
chosen.push(library.find_space(space)?);
}
let device = nibkeep_node::NewDevice {
phone: *phone,
spaces: (!spaces.is_empty()).then(|| chosen.clone()),
};
let pairing = (ai_agent.as_deref(), &chosen[..], *give_secrets);
pair_command(
library,
(pairing, &device),
cli,
environment,
timings,
output,
)
}
DeviceCommand::Revoke { device, yes, codes } => revoke_command(
library,
(device, *yes, *codes),
cli.json,
environment,
output,
),
DeviceCommand::Mark { .. } => mark_command(library, command, cli.json, environment, output),
DeviceCommand::Review => output::set_aside(
&library.set_aside()?,
&library.replicas()?,
cli.json,
output,
),
DeviceCommand::Accept { device, yes } => {
accept_command(library, (device, *yes), cli.json, environment, output)
}
}
}
fn mark_command<E: Environment>(
library: &mut Library,
command: &DeviceCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let DeviceCommand::Mark {
device,
archive,
everyday,
away,
home,
keeps,
waits,
new_spaces,
} = command
else {
unreachable!("only nib device mark comes here");
};
let (chosen, name) = one_device(library, device)?;
let this = library.user_and_device()?.1.id == chosen;
if let Some(new_spaces) = new_spaces {
if !this {
return Err(CliError::NewSpacesElsewhere(
name.clone().unwrap_or_else(|| device.clone()),
));
}
let now = environment.now();
library.set_takes_new_spaces(*new_spaces == NewSpacesArg::Take, now, environment.rng())?;
}
let takes = if this {
Some(library.takes_new_spaces()?)
} else {
None
};
let mut marks = library.device_marks(chosen)?;
if let Some(Waits(waits)) = waits {
marks.waits = *waits;
}
if *archive {
marks.role = DeviceRole::Archive;
}
if *everyday {
marks.role = DeviceRole::Everyday;
}
if *away {
marks.away = true;
}
if *home {
marks.away = false;
}
if let Some(Keeps(keeps)) = keeps {
marks.keeps = *keeps;
}
if *archive || *everyday || *away || *home || keeps.is_some() || waits.is_some() {
library.set_device_marks(chosen, marks, environment.now(), environment.rng())?;
}
output::device_marked(
(name.as_deref(), chosen),
(marks, takes, new_spaces.is_some()),
json,
output,
)
}
fn revoke_command<E: Environment>(
library: &mut Library,
(device, yes, codes): (&str, bool, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let mut replicas = library.to_revoke(device)?;
let ids: Vec<_> = replicas.iter().map(|replica| replica.id).collect();
let out_of_reach = library.out_of_reach(&ids).unwrap_or_default();
let mut made = library.recovery_codes_made_by(&ids)?;
let mut elsewhere = Vec::new();
if yes && !replicas.is_empty() {
let spaces = library.revoke(&ids, environment.now(), environment.rng())?;
elsewhere = spaces
.iter()
.copied()
.zip(space_names(library, &spaces))
.collect();
elsewhere.sort_by(|a, b| a.1.cmp(&b.1));
if codes {
for code in &made {
let now = environment.now();
library.revoke_recovery_code(&code.record.to_string(), now, environment.rng())?;
}
let records: Vec<_> = made.iter().map(|code| code.record).collect();
made = library
.recovery_codes()?
.into_iter()
.filter(|code| records.contains(&code.record))
.collect();
}
replicas = library
.replicas()?
.into_iter()
.filter(|replica| ids.contains(&replica.id))
.collect();
}
output::revoked(
&replicas,
(&made, codes),
(yes, &elsewhere),
&out_of_reach,
json,
output,
)?;
if yes || replicas.is_empty() {
Ok(())
} else {
Err(CliError::UnconfirmedRevoke)
}
}
fn accept_command<E: Environment>(
library: &mut Library,
(device, confirmed): (&str, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let named: Vec<_> = library
.replicas_named(device)?
.into_iter()
.map(|replica| replica.id)
.collect();
let changes: Vec<_> = library
.set_aside()?
.into_iter()
.filter(|aside| {
aside.acceptable
&& aside
.replica
.is_some_and(|replica| named.contains(&replica))
})
.map(|aside| aside.change)
.collect();
let accepted = if confirmed {
library.accept_set_aside(&changes, environment.now(), environment.rng())?
} else {
changes.len()
};
output::accepted(accepted, confirmed, json, output)?;
if confirmed || accepted == 0 {
Ok(())
} else {
Err(CliError::UnconfirmedAccept)
}
}
fn sync_command<E: Environment>(
library: &mut Library,
cli: &Cli,
wait: Duration,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
if library.peers()?.is_empty() {
return Err(NodeError::NoOtherReplicas.into());
}
let waited = Instant::now();
let _role = loop {
if let Some(role) = library.take_role()? {
break role;
}
if library.sync_records(UnwrapErr(SysRng))?.holder()?.is_some() {
if let Some(asked) = ask_to_sync(library, wait, cli, environment, output)? {
return asked;
}
continue;
}
if waited.elapsed() > wait + ASK_WAIT {
return Err(CliError::NotAnswered("another program".to_owned()));
}
std::thread::sleep(Duration::from_millis(100));
};
let network = library.network(cli.network(false))?;
output::progress("Looking for your other devices…", json, output)?;
let now = clock(environment);
let synced = nibkeep_node::sync_with_others(library, &network, wait, &now, environment.rng())?;
output::synced_with(&synced, json, output)?;
if library.is_revoked()? {
return Err(NodeError::Revoked.into());
}
match synced.iter().filter(|with| with.synced.is_err()).count() {
0 => Ok(()),
failed => Err(CliError::SyncsFailed(failed)),
}
}
fn pull_command<E: Environment>(
library: &mut Library,
cli: &Cli,
(wait, update): (Duration, (bool, bool, bool)),
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
let mut synced = Vec::new();
let sync = if json {
sync_command(library, cli, wait, environment, &mut synced)
} else {
sync_command(library, cli, wait, environment, output)
};
let mut updated = Vec::new();
if let Err(error) =
trees::update_here(library, update, json, (environment, timings), &mut updated)
{
if let Err(failed) = &sync {
environment.note(&format!("the sync failed too: {failed}"));
}
return Err(error);
}
if json {
let read = |printed: &[u8]| -> Result<serde_json::Value, CliError> {
if printed.iter().all(u8::is_ascii_whitespace) {
return Ok(serde_json::Value::Null);
}
serde_json::from_slice(printed).map_err(|error| CliError::Io(io::Error::other(error)))
};
let pulled = serde_json::json!({ "sync": read(&synced)?, "update": read(&updated)? });
output::print_json(&pulled, output)?;
} else {
output.write_all(&updated)?;
}
sync
}
const ASK_WAIT: Duration = Duration::from_mins(2);
fn ask_to_sync<E: Environment>(
library: &mut Library,
wait: Duration,
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<Option<Result<(), CliError>>, CliError> {
let json = cli.json;
let records = library.sync_records(UnwrapErr(SysRng))?;
let Some(holder) = records.holder()? else {
return Ok(None);
};
output::progress(&format!("Asking {} to sync…", holder.program), json, output)?;
let asked = environment.now();
let ask = records.ask(None, asked)?;
let waited = Instant::now();
while records.answered(ask)?.is_none() {
if library.take_role()?.is_some() {
return Ok(None);
}
if waited.elapsed() > wait + ASK_WAIT {
return Err(CliError::NotAnswered(holder.program));
}
std::thread::sleep(Duration::from_millis(100));
}
library.catch_up()?;
let failed = output::asked(
&library.peers()?,
&records.synced_since(asked)?,
json,
output,
)?;
if library.is_revoked()? {
return Err(NodeError::Revoked.into());
}
Ok(Some(match failed {
0 => Ok(()),
failed => Err(CliError::SyncsFailed(failed)),
}))
}
enum Making<'a> {
New(Option<&'a str>, Option<&'a Languages>),
Join(&'a PairingCode, bool),
Recover(Option<&'a Path>, &'a [String]),
FromCopy,
}
fn new_library<E: Environment>(
directory: &Path,
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<Library, CliError> {
let (making, device, passphrase, allow_fat) = match &cli.command {
Command::Init {
name,
device,
passphrase,
languages,
join,
secrets,
allow_fat,
..
} => {
let making = match (join, name) {
(Some(code), _) => Making::Join(code, *secrets),
(None, name) => Making::New(name.as_deref(), languages.as_ref()),
};
(making, device.as_deref(), *passphrase, *allow_fat)
}
Command::Recovery {
command: RecoveryCommand::Restore { source, keep, new },
} => (
Making::Recover(source.as_deref(), keep),
new.device.as_deref(),
new.passphrase,
new.allow_fat,
),
Command::Recovery {
command: RecoveryCommand::FromCopy { new },
} => (
Making::FromCopy,
new.device.as_deref(),
new.passphrase,
new.allow_fat,
),
_ => unreachable!("only nib init and nib recovery make a library"),
};
if allow_fat {
Library::allow_fat(directory)?;
}
if matches!(
Library::replica_folder(directory),
Err(NodeError::NoLibrary | NodeError::Copied)
) {
Library::check_place(directory).map_err(|error| no_journal(error.into(), directory))?;
}
let protection = (passphrase, cli.passphrase_file.as_deref());
match making {
Making::Join(code, secrets) => join_command(
directory,
(code, device, secrets),
protection,
cli,
environment,
timings,
output,
),
Making::New(name, languages) => init_command(
directory,
(name, device, languages),
protection,
environment,
timings,
),
Making::Recover(source, keep) => recover_command(
directory,
(source, device, keep),
protection,
cli,
environment,
timings,
output,
),
Making::FromCopy => from_copy_command(
directory,
device,
protection,
cli,
environment,
timings,
output,
),
}
.map_err(|error| no_journal(error, directory))
}
fn at_login_command<E: Environment>(
switch: Switch,
directory: &Path,
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let state = environment.state_folder().ok_or(CliError::NoStateFolder)?;
let directory = std::path::absolute(directory)?;
let keystore = matches!(
Library::protection(&directory),
Ok(Protection::Keystore { .. })
);
if switch == Switch::Off {
let replica = if keystore {
open(&directory, None, environment, timings)
.ok()
.and_then(|library| own_replica(&library).ok())
} else {
None
};
let entry = environment.login_entry();
let turned_off = at_login::turn_off(&state, (&directory, replica), entry.as_ref())?;
return output::at_login_off(&turned_off, cli.json, output);
}
if !keystore {
Library::protection(&directory).map_err(|error| opening(error, &directory))?;
return Err(CliError::AtLoginPassphrase);
}
let program = environment.sync_program().ok_or(CliError::NoSyncProgram)?;
let library = open(&directory, None, environment, timings)
.map_err(|error| opened_error(error, &directory))?;
let served = at_login::Served {
replica: own_replica(&library)?,
directory,
};
drop(library);
let entry = environment.login_entry();
let version_of = |listed: &Path| environment.sync_version(listed);
let turned_on = at_login::turn_on(&state, served, (&program, &version_of), entry.as_ref())
.map_err(|error| match error {
NodeError::NotInKeystore => CliError::AtLoginPassphrase,
other => CliError::Node(other),
})?;
let firewall = environment.open_firewall();
if let Some(start) = &turned_on.start {
environment.start_sync(start)?;
}
output::at_login_on(&turned_on.entry, firewall, cli.json, output)
}
fn own_replica(library: &Library) -> Result<EntityId, CliError> {
library
.replicas()?
.into_iter()
.find(|replica| replica.this)
.map(|replica| replica.id)
.ok_or_else(|| {
CliError::Node(NodeError::Damaged(
"the library lists no replica of its own".to_owned(),
))
})
}
fn opening(error: NodeError, directory: &Path) -> CliError {
match error {
NodeError::Unfinished => unfinished(directory),
NodeError::Copied => CliError::IsCopy(directory.to_owned()),
NodeError::UncleanRemoval => CliError::UncleanRemoval(directory.to_owned()),
other => CliError::Node(other),
}
}
fn opened_error(error: CliError, directory: &Path) -> CliError {
match error {
CliError::Node(error) => opening(error, directory),
other => other,
}
}
fn turn_off_at_login<E: Environment>(directory: &Path, environment: &mut E) {
let Some(state) = environment.state_folder() else {
return;
};
let entry = environment.login_entry();
let turned_off = std::path::absolute(directory)
.map_err(CliError::from)
.and_then(|directory| {
Ok(at_login::turn_off(
&state,
(&directory, None),
entry.as_ref(),
)?)
});
match turned_off {
Ok(turned_off) => {
if turned_off.removed {
environment.note(AT_LOGIN_TURNED_OFF);
}
if let Some(error) = &turned_off.entry_failed {
environment.note(&entry_not_removed(error));
}
}
Err(error) => environment.note(&format!(
"nib: could not turn syncing from login off for this library ({error}); nibkeep-sync turns it off as it finds the passphrase"
)),
}
}
fn entry_not_removed(error: &str) -> String {
format!(
"nib: the login entry could not be removed ({error}); nib sync --at-login off tries again"
)
}
const 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";
fn at_login_state<E: Environment>(
(directory, replica): (&Path, Option<EntityId>),
environment: &E,
) -> Option<at_login::AtLoginStatus> {
let state = environment.state_folder()?;
let directory = std::path::absolute(directory).ok()?;
let entry = environment.login_entry();
let status = at_login::status(&state, (&directory, replica), entry.as_ref());
status.on.then_some(status)
}
fn serve_command<E: Environment>(
library: Library,
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
let closed = library.close();
let stop = Arc::new(AtomicBool::new(false));
environment.stop_on_interrupt(Arc::clone(&stop));
let role = if let Some(role) = Role::take(&closed)? {
role
} else {
let program = closed
.open()?
.sync_records(UnwrapErr(SysRng))?
.holder()?
.map_or_else(|| "Another program".to_owned(), |holder| holder.program);
output::progress(
&format!(
"{program} syncs this device; this one takes over when it ends. Stop with Ctrl-C."
),
json,
output,
)?;
let Some(role) = Role::wait(&closed, &stop)? else {
return Ok(());
};
role
};
output::progress(
"Syncing this device with your other devices; stop with Ctrl-C.",
json,
output,
)?;
let now = clock(environment);
let holding = Holding {
program: "nib sync --serve",
network: cli.network(true),
known: Vec::new(),
quiet: Holding::QUIET,
appear_wait: Holding::APPEAR_WAIT,
check: nibkeep_node::Pace::DEFAULT,
stop: &stop,
now: &now,
};
let mut printed = Ok(());
nibkeep_node::hold(
&closed,
role,
&holding,
&|| UnwrapErr(SysRng),
&mut |held| {
if printed.is_ok() {
printed = output::held(&held, json, output);
if printed.is_err() {
stop.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
},
)?;
printed
}
fn join_command<E: Environment>(
directory: &Path,
(code, device, secrets): (&PairingCode, Option<&str>, bool),
(passphrase, file): (bool, Option<&Path>),
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<Library, CliError> {
if Library::exists(directory) {
match Library::protection(directory) {
Err(NodeError::Copied) => {}
Err(NodeError::Unfinished) => return Err(unfinished(directory)),
_ => return Err(NodeError::Exists.into()),
}
}
let device = device_name(device, environment);
let passphrase = new_passphrase((passphrase, file), environment, timings)?;
let protection = match &passphrase {
Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
None => NewProtection::Keystore {
service: KEYSTORE_SERVICE,
},
};
let secrets_passphrase = if secrets {
let typed = ask_twice(
environment,
timings,
(
"A passphrase for the secrets on this device, not the library's: ",
"The passphrase again: ",
),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
)?;
Some(typed)
} else {
None
};
let json = cli.json;
let secrets_params = environment.passphrase_params();
let mut joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
let beside_copies = !Library::copies_in(directory).is_empty();
if let Some(typed) = secrets_passphrase.as_ref().filter(|_| !beside_copies) {
let protection = NewProtection::Passphrase(typed, secrets_params);
joining = joining.asking_for_secrets(protection, environment.rng());
}
let network = joining.network(cli.network(false))?;
output::progress("Looking for the device that shows the code…", json, output)?;
let now = clock(environment);
let joined = nibkeep_node::join(
directory,
joining,
&network,
code,
&protection,
FIND_SPONSOR,
&now,
environment.rng(),
)
.map_err(|error| match error {
error @ NodeError::Keys(KeysError::Keystore(_)) => CliError::Keystore(error),
other => CliError::Node(other),
})?;
let mut library = joined.library;
library.lock_secrets();
let secrets = if secrets {
Some((library.secrets_state()?, library.is_ai_agent()?))
} else {
None
};
let copies = take_in_copies(&mut library, environment)?;
if let (Some(typed), Some(copies)) = (&secrets_passphrase, &copies) {
let protection = NewProtection::Passphrase(typed, secrets_params);
if let Err(error) = secrets_from_copies(
&mut library,
&copies.folders,
&protection,
environment,
timings,
) {
environment.note(&format!(
"the copy's secrets were not taken: {error}; nib secret from-copy takes them"
));
}
}
let secrets = match secrets {
Some(_) => Some((library.secrets_state()?, library.is_ai_agent()?)),
None => None,
};
output::joined(
(&joined.synced, joined.refused),
secrets,
copies.as_ref(),
json,
output,
)?;
Ok(library)
}
fn secrets_from_copies<E: Environment>(
library: &mut Library,
copies: &[PathBuf],
protection: &NewProtection<'_>,
environment: &mut E,
timings: &mut Timings,
) -> Result<usize, CliError> {
for folder in copies {
let copy = nibkeep_node::ReplicaCopy {
folder: folder.clone(),
replica: None,
};
let Ok((_, Some(kept))) = copy.protections() else {
continue;
};
let typed;
let unlocker = match kept {
Protection::Keystore { .. } => Unlocker::Keystore,
Protection::Passphrase { .. } => {
typed = ask_once(
environment,
timings,
"The passphrase of the copy's secrets, or nothing to leave them: ",
)?;
if typed.is_empty() {
return Ok(0);
}
Unlocker::Passphrase(&typed)
}
};
let now = environment.now();
return Ok(library.take_secrets_from_copy(
folder,
&unlocker,
protection,
now,
environment.rng(),
)?);
}
Ok(0)
}
fn from_copy_secrets_command<E: Environment>(
library: &mut Library,
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let copies: Vec<PathBuf> = library
.copies()
.into_iter()
.map(|copy| copy.folder)
.collect();
let typed = ask_twice(
environment,
timings,
(
"A passphrase for the secrets on this device, not the library's: ",
"The passphrase again: ",
),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
)?;
let protection = NewProtection::Passphrase(&typed, environment.passphrase_params());
let taken = secrets_from_copies(library, &copies, &protection, environment, timings);
library.lock_secrets();
match taken? {
0 => Err(CliError::NoSecretsInCopies),
taken => output::progress(
&format!("Took {taken} secrets keys from the copy: this device holds the secrets."),
json,
output,
),
}
}
fn from_copy_command<E: Environment>(
directory: &Path,
device: Option<&str>,
(passphrase, file): (bool, Option<&Path>),
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<Library, CliError> {
if Library::replica_folder(directory).is_ok() {
return Err(NodeError::Exists.into());
}
let copies = Library::copies_in(directory);
let copy = match copies.as_slice() {
[copy] => copy,
[] => return Err(CliError::NoCopy(directory.to_owned())),
_ => return Err(CliError::SeveralCopies(directory.to_owned())),
};
let (kept, secrets_kept) = copy.protections()?;
let typed;
let unlocker = match kept {
Protection::Keystore { .. } => Unlocker::Keystore,
Protection::Passphrase { .. } => {
typed = ask_once(
environment,
timings,
"The passphrase of the copy, the library's: ",
)?;
Unlocker::Passphrase(&typed)
}
};
let device = device_name(device, environment);
let new_passphrase = new_passphrase((passphrase, file), environment, timings)?;
let protection = match &new_passphrase {
Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
None => NewProtection::Keystore {
service: KEYSTORE_SERVICE,
},
};
let mut copy_secrets = None;
let secrets_typed;
if let Some(kept) = secrets_kept {
let typed = match kept {
Protection::Keystore { .. } => None,
Protection::Passphrase { .. } => Some(ask_once(
environment,
timings,
"The passphrase of the copy's secrets, or nothing to leave them: ",
)?),
};
if typed.as_ref().is_none_or(|typed| !typed.is_empty()) {
let new = ask_twice(
environment,
timings,
(
"A passphrase for the secrets on this device, not the library's: ",
"The passphrase again: ",
),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
)?;
secrets_typed = (typed, new);
copy_secrets = Some(&secrets_typed);
}
}
let secrets_params = environment.passphrase_params();
let secrets_unlocker = copy_secrets.map(|(typed, _)| match typed {
Some(typed) => Unlocker::Passphrase(typed),
None => Unlocker::Keystore,
});
let secrets_protection =
copy_secrets.map(|(_, new)| NewProtection::Passphrase(new, secrets_params));
let joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
let now = clock(environment);
let library = Library::add_from_copy(
directory,
(©.folder, &unlocker),
joining,
&protection,
secrets_unlocker.as_ref().zip(secrets_protection.as_ref()),
&now,
environment.rng(),
)?;
output::progress(
"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.",
cli.json,
output,
)?;
Ok(library)
}
fn recover_command<E: Environment>(
directory: &Path,
(source, device, keep): (Option<&Path>, Option<&str>, &[String]),
(passphrase, file): (bool, Option<&Path>),
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<Library, CliError> {
let source = match source {
Some(source) => absolute(source, environment)?,
None => directory.to_owned(),
};
let replaces = Library::exists(directory) && Library::recovery_replaces(directory, &source);
if Library::exists(directory) && !replaces {
match Library::protection(directory) {
Err(NodeError::Copied | NodeError::RecoveryCutShort) => {}
Err(NodeError::Unfinished) => return Err(unfinished(directory)),
_ => return Err(NodeError::Exists.into()),
}
}
if replaces
&& matches!(
Library::protection(directory),
Ok(Protection::Keystore { .. })
)
&& environment.keystore()
&& Library::open(directory, &Unlocker::Keystore).is_ok()
{
return Err(CliError::StillUnlocks);
}
let code = typed_recovery_code("Your recovery code: ", environment, cli.json, output)?;
Library::check_recovery_source(&source, &code)?;
let device = device_name(device, environment);
let new_passphrase = new_passphrase((passphrase, file), environment, timings)?;
let protection = match &new_passphrase {
Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
None => NewProtection::Keystore {
service: KEYSTORE_SERVICE,
},
};
let joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
let now = clock(environment);
let mut recovering = Library::start_recovery(
directory,
(&source, &code),
joining,
&protection,
&now,
environment.rng(),
)?;
let kept = devices_kept(&recovering, keep, cli.json, environment)?;
recovering.keep(&kept)?;
let secrets_passphrase = if recovering.holds_secrets() {
Some(recovered_secrets_passphrase(
environment,
timings,
new_passphrase.as_deref().map(String::as_str),
)?)
} else {
None
};
let secrets_params = environment.passphrase_params();
let secrets = secrets_passphrase
.as_ref()
.map(|typed| NewProtection::Passphrase(typed, secrets_params));
let (mut library, recovered) = recovering.finish(secrets.as_ref(), &now, environment.rng())?;
library.lock_secrets();
let spaces = sorted_space_names(&library, &recovered.spaces);
let elsewhere = sorted_space_names(&library, &recovered.revoked_elsewhere);
let old_size = match &recovered.from {
nibkeep_node::RecoveredFrom::Library {
set_aside, folder, ..
} => folder_size(set_aside.as_ref().unwrap_or(folder)),
nibkeep_node::RecoveredFrom::Backup { .. } => 0,
};
output::recovered(
&recovered,
(&spaces, &elsewhere, old_size),
cli.json,
output,
)?;
Ok(library)
}
fn devices_kept<E: Environment>(
recovering: &nibkeep_node::Recovering<'_>,
named: &[String],
json: bool,
environment: &mut E,
) -> Result<Vec<EntityId>, CliError> {
if !named.is_empty() {
let mut kept = Vec::new();
for target in named {
kept.extend(
recovering
.others_named(target)?
.into_iter()
.map(|replica| replica.id),
);
}
return Ok(kept);
}
if json || !environment.can_ask() {
return Ok(Vec::new());
}
let mut devices: BTreeMap<EntityId, Vec<Replica>> = BTreeMap::new();
for replica in recovering.others()? {
let device = match replica.device {
Some(device) if !replica.ai_agent => device,
_ => replica.id,
};
devices.entry(device).or_default().push(replica);
}
let mut asked: Vec<(String, EntityId, Vec<Replica>)> = devices
.into_iter()
.map(|(device, replicas)| (output::kept_device_text(&replicas), device, replicas))
.collect();
asked.sort_by(|a, b| (&a.0, a.1).cmp(&(&b.0, b.1)));
let alike: Vec<bool> = asked
.iter()
.map(|(text, ..)| asked.iter().filter(|(other, ..)| other == text).count() > 1)
.collect();
let mut kept = Vec::new();
for ((text, device, replicas), alike) in asked.into_iter().zip(alike) {
let text = if alike {
format!("{text} {}", output::short(device))
} else {
text
};
let answer = environment.ask(&output::keep_question(&text))?;
if answer.is_some_and(|answer| matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"))
{
kept.extend(replicas.iter().map(|replica| replica.id));
}
}
Ok(kept)
}
fn recovered_secrets_passphrase<E: Environment>(
environment: &mut E,
timings: &mut Timings,
library: Option<&str>,
) -> Result<zeroize::Zeroizing<String>, CliError> {
let mut tries = 0;
loop {
tries += 1;
let typed = ask_twice(
environment,
timings,
(
"Your recovery code holds your secrets. A passphrase for them on this device, not the library's: ",
"The passphrase again: ",
),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
);
let error = match typed {
Ok(typed) if library.is_some_and(|library| *typed == *library) => {
CliError::Node(NodeError::LibraryPassphrase)
}
Ok(typed) => return Ok(typed),
Err(error @ (CliError::EmptyPassphrase | CliError::PassphrasesDiffer)) => error,
Err(error) => return Err(error),
};
if tries == 3 {
return Err(error);
}
environment.note(&format!("{error}; type it again"));
}
}
fn take_in_copies<E: Environment>(
library: &mut Library,
environment: &mut E,
) -> Result<Option<output::Copies>, CliError> {
let copies = library.copies();
if copies.is_empty() {
return Ok(None);
}
let now = clock(environment);
let taken = library.take_in_copies(&now)?;
let replicas = library.replicas()?;
let mut devices: Vec<String> = copies
.iter()
.filter_map(|copy| {
let (replica, _) = copy.replica?;
let known = replicas.iter().find(|known| known.id == replica)?;
known.device_name.clone().or_else(|| known.name.clone())
})
.collect();
devices.sort();
devices.dedup();
let size = copies.iter().map(|copy| folder_size(©.folder)).sum();
let secrets_left = library.secrets_state()? != nibkeep_node::SecretsState::Here
&& copies.iter().any(|copy| {
copy.protections()
.is_ok_and(|(_, secrets)| secrets.is_some())
});
Ok(Some(output::Copies {
taken,
secrets_left,
devices,
folders: copies.into_iter().map(|copy| copy.folder).collect(),
size,
}))
}
fn folder_size(folder: &Path) -> u64 {
std::fs::read_dir(folder)
.into_iter()
.flatten()
.flatten()
.map(|entry| match entry.file_type() {
Ok(kind) if kind.is_dir() => folder_size(&entry.path()),
_ => entry.metadata().map_or(0, |metadata| metadata.len()),
})
.sum()
}
fn user_names<E: Environment>(
given: Option<&str>,
environment: &E,
) -> Result<(String, Option<String>), CliError> {
if let Some(given) = given {
return Ok((given.to_owned(), None));
}
let account = environment.account();
let user = account
.name
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty())
.ok_or(CliError::NoAccountName)?;
let person = account
.full_name
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty() && *name != user);
Ok((user, person))
}
fn device_name<E: Environment>(given: Option<&str>, environment: &E) -> String {
given.map_or_else(
|| {
Some(environment.computer_name())
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "device".to_owned())
},
str::to_owned,
)
}
fn parse_code(text: &str) -> Result<PairingCode, String> {
text.parse()
.map_err(|error: nibkeep_node::NotACode| error.to_string())
}
fn syncs_failed(failed: usize) -> String {
if failed == 1 {
"a device could not be synced with".to_owned()
} else {
format!("{failed} devices could not be synced with")
}
}
const CANDIDATES_LISTED: usize = 10;
fn candidates_named<E: Environment>(
library: &Library,
error: CliError,
environment: &E,
) -> CliError {
let CliError::Node(NodeError::Ambiguous {
reference,
candidates,
}) = error
else {
return error;
};
let personal = library.personal_space();
let day = dating(environment, environment.now(), None).day;
let mut listed = Vec::new();
let mut members: std::collections::BTreeMap<EntityId, Vec<nibkeep_node::Listed>> =
std::collections::BTreeMap::new();
for &id in candidates.iter().take(CANDIDATES_LISTED) {
let space = library.space_of(id).ok().flatten().unwrap_or(personal);
let (name, types) = match library.entity(space, id, day) {
Ok(Some(view)) if view.id == id => (view.name, view.types),
Ok(Some(view)) => {
let of_view = members
.entry(view.id)
.or_insert_with(|| library.merged(space, view.id).unwrap_or_default());
let name = of_view
.iter()
.find(|member| member.id == id)
.and_then(|member| member.name.clone());
let types = library.own_types(space, id).unwrap_or_default();
(name.or(view.name), types)
}
_ => (None, Vec::new()),
};
listed.push(nibkeep_node::Listed {
id,
name,
types,
via: None,
});
}
CliError::Ambiguous {
reference,
count: candidates.len(),
candidates: output::candidates(&listed, candidates.len()),
}
}
fn files_failed(failed: usize) -> String {
if failed == 1 {
"a file could not be added".to_owned()
} else {
format!("{failed} files could not be added")
}
}
fn unsound_export(problems: usize) -> String {
if problems == 1 {
"the export has a problem".to_owned()
} else {
format!("the export has {problems} problems")
}
}
fn unsound(problems: usize) -> String {
if problems == 1 {
"the library has a problem".to_owned()
} else {
format!("the library has {problems} problems")
}
}
fn edits(
changes: &[String],
forms: Forms<'_>,
view: &EntityView,
library: &Library,
space: nibkeep_base::SpaceId,
) -> Result<Vec<Edit>, CliError> {
let types = library.types(space)?;
let mut sets: Vec<(nibkeep_model::FieldName, Vec<nibkeep_model::Value>)> = Vec::new();
let mut cleared = std::collections::BTreeSet::new();
let mut others = Vec::new();
let mut kinds = view.types.clone();
let (mut given, mut taken) = (Vec::new(), Vec::new());
let mut rest = Vec::new();
for change in changes {
let (left, text) = change
.split_once('=')
.ok_or_else(|| CliError::Assignment(change.clone()))?;
let (field, how) = match (left.strip_suffix('+'), left.strip_suffix('-')) {
(Some(field), _) => (field, '+'),
(_, Some(field)) => (field, '-'),
_ => (left, '='),
};
let of_types = field == nibkeep_model::fields::TYPE.as_str()
|| (field == "type"
&& matches!(
types::field_named(field, &types, &kinds),
Err(CliError::NoField { .. })
));
if !of_types {
rest.push((change, field, how, text));
continue;
}
match how {
'+' => {
let name = types::type_named(text, &types)?;
kinds.push(name.clone());
given.push(Edit::AddType(name));
}
'-' => taken.push(Edit::RemoveType(types::type_of(text, &view.types, &types)?)),
_ => return Err(CliError::TypeSet),
}
}
for (change, field, how, text) in rest {
let field = types::field_named(field, &types, &kinds)?;
if is_secret(library, space, &field) {
return Err(CliError::SecretField(field));
}
if text.is_empty() {
if how != '=' {
return Err(CliError::Assignment(change.clone()));
}
if sets
.iter()
.any(|(set, values)| *set == field && !values.is_empty())
{
return Err(CliError::SetAndCleared(field));
}
if cleared.insert(field.clone()) {
sets.push((field, Vec::new()));
}
continue;
}
let value = types::value(text, &field, &types, library, space)?;
match how {
'+' if !matches!(forms, Forms::No) => {
let of = match forms {
Forms::Of(of) => Some(types::value(of, &field, &types, library, space)?),
_ => None,
};
others.push(Edit::AddForm { field, of, value });
}
'-' if !matches!(forms, Forms::No) => others.push(Edit::RemoveForm(field, value)),
'+' => others.push(Edit::Add(field, value)),
'-' => others.push(Edit::Remove(field, value)),
_ => {
if cleared.contains(&field) {
return Err(CliError::SetAndCleared(field));
}
match sets.iter_mut().find(|(set, _)| *set == field) {
Some((_, values)) => values.push(value),
None => sets.push((field, vec![value])),
}
}
}
}
if !matches!(forms, Forms::No)
&& !others
.iter()
.any(|edit| matches!(edit, Edit::AddForm { .. } | Edit::RemoveForm(..)))
{
return Err(CliError::NoForms);
}
Ok(given
.into_iter()
.chain(taken)
.chain(
sets.into_iter()
.map(|(field, values)| Edit::Set(field, values)),
)
.chain(others)
.collect())
}
fn system_languages(locales: &[String]) -> Languages {
let mut ranges: Vec<String> = Vec::new();
for written in locales {
let script = match written.rsplit_once('@').map(|(_, modifier)| modifier) {
Some("latin") => Some("Latn"),
Some("cyrillic") => Some("Cyrl"),
_ => None,
};
let locale = written.split(['.', '@']).next().unwrap_or_default();
if locale.is_empty() || locale == "C" || locale == "POSIX" {
continue;
}
let mut subtags = locale.split(['_', '-']);
let mut range = subtags.next().unwrap_or_default().to_owned();
let named = subtags
.next()
.filter(|subtag| subtag.len() == 4 && subtag.chars().all(|c| c.is_ascii_alphabetic()));
if let Some(script) = named.or(script) {
range = format!("{range}-{script}");
}
if let Ok(parsed) = range.parse::<Languages>() {
let range = parsed.to_string();
if !range.is_empty() && !ranges.contains(&range) {
ranges.push(range);
}
}
}
ranges.join(", ").parse().unwrap_or_default()
}
fn parse_languages(text: &str) -> Result<Languages, String> {
text.parse()
.map_err(|error: ParseLanguagesError| error.to_string())
}
fn parse_tag(text: &str) -> Result<Tag, String> {
Tag::parse(text).ok_or_else(|| {
"a language tag is written as in BCP 47, such as en, uk or uk-Latn".to_owned()
})
}
fn dating<E: Environment>(environment: &E, now: u64, on: Option<Day>) -> Dating {
match on {
Some(day) => Dating::on(day),
None => Dating::today(now, environment.offset_minutes())
.or_else(|| Dating::today(now, 0))
.expect("the time has a day in UTC"),
}
}
fn parse_day(text: &str) -> Result<Day, String> {
text.parse()
.map_err(|_| "a day is written as YYYY-MM-DD, such as 2000-01-01".to_owned())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Moment {
Day(jiff::civil::Date),
Local(jiff::civil::DateTime),
Exact(jiff::Timestamp),
}
impl Moment {
fn resolve(self, zone: &jiff::tz::TimeZone) -> Result<(Option<u64>, Day), CliError> {
let unplaced = || CliError::Moment("it cannot be placed in local time".to_owned());
let timestamp = match self {
Self::Day(date) => date
.tomorrow()
.ok()
.and_then(|next| next.to_zoned(zone.clone()).ok())
.and_then(|next| {
next.timestamp()
.checked_sub(jiff::SignedDuration::from_millis(1))
.ok()
})
.ok_or_else(unplaced)?,
Self::Local(time) => time
.to_zoned(zone.clone())
.map_err(|_| unplaced())?
.timestamp(),
Self::Exact(timestamp) => timestamp,
};
let millis = u64::try_from(timestamp.as_millisecond()).ok();
let date = match self {
Self::Day(date) => date,
_ => timestamp.to_zoned(zone.clone()).date(),
};
let day = Day::from_ymd(
i64::from(date.year()),
date.month().unsigned_abs(),
date.day().unsigned_abs(),
)
.expect("every date of a calendar is a day");
Ok((millis, day))
}
}
fn parse_moment(text: &str) -> Result<Moment, String> {
let wrong = || {
"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"
.to_owned()
};
if text.len() == "YYYY-MM-DD".len() {
return text
.parse::<jiff::civil::Date>()
.map(Moment::Day)
.map_err(|_| wrong());
}
if let Ok(timestamp) = text.parse::<jiff::Timestamp>() {
return Ok(Moment::Exact(timestamp));
}
text.parse::<jiff::civil::DateTime>()
.map(Moment::Local)
.map_err(|_| wrong())
}
fn parse_edtf(text: &str) -> Result<Edtf, String> {
text.parse()
.map_err(|error: nibkeep_time::ParseEdtfError| error.to_string())
}
fn show(
library: &Library,
space: nibkeep_base::SpaceId,
entity: nibkeep_base::EntityId,
when: When,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
show_added(library, space, entity, &[], when, json, output)
}
#[derive(Clone, Copy, Debug)]
struct When {
day: Day,
as_of: Option<u64>,
given: Option<Day>,
}
impl When {
const fn on(day: Day) -> Self {
Self {
day,
as_of: None,
given: None,
}
}
fn given(day: Day, given: Option<Day>) -> Self {
Self {
given,
..Self::on(day)
}
}
}
fn show_added(
library: &Library,
space: nibkeep_base::SpaceId,
entity: nibkeep_base::EntityId,
recorded_before: &[nibkeep_base::EntityId],
when: When,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let When { day, as_of, given } = when;
let view: Option<EntityView> = match as_of {
Some(millis) => library.entity_as_of(space, entity, day, millis)?,
None => library.entity(space, entity, day)?,
};
let view = view.ok_or_else(|| NodeError::NoEntity(entity.to_string()))?;
let links = match as_of {
Some(millis) => library.links_to_as_of(space, view.id, day, millis, LINKS_SHOWN)?,
None => library.links_to_anywhere(space, view.id, day, LINKS_SHOWN)?,
};
let merged = match as_of {
Some(millis) => library.merged_as_of(space, view.id, millis)?,
None => library.merged(space, view.id)?,
};
let name_of = |entity| match as_of {
Some(millis) => library.name_as_of(space, entity, millis).ok().flatten(),
None => library
.name_anywhere(entity)
.ok()
.flatten()
.or_else(|| library.name(space, entity).ok().flatten()),
};
let mut secret = library.secret_fields_of(space, &view.types)?;
secret.retain(|field| !view.fields.iter().any(|shown| shown.field == *field));
let more = match as_of {
Some(_) => None,
None => Some(given.map_or_default(|day| format!(" --on {day}"))),
};
let thumbnail = if as_of.is_none() && view.types.contains(&FILE) {
library.thumbnail(space, view.id)?
} else {
None
};
let shown = output::Shown {
view: &view,
merged: &merged,
secret: &secret,
links: &links,
more: more.as_deref(),
recorded_before,
thumbnail: thumbnail.as_ref(),
};
output::entity(&shown, &name_of, json, output)
}
fn init_command<E: Environment>(
directory: &Path,
(name, device, languages): (Option<&str>, Option<&str>, Option<&Languages>),
passphrase: (bool, Option<&Path>),
environment: &mut E,
timings: &mut Timings,
) -> Result<Library, CliError> {
let (user, person) = user_names(name, environment)?;
let device = device_name(device, environment);
let languages = languages
.cloned()
.unwrap_or_else(|| system_languages(&environment.languages()));
let new = NewLibrary::new(&user, &device, APP)
.with_person(person.as_deref())
.with_languages(languages);
init(directory, &new, passphrase, environment, timings)
}
fn show_command<E: Environment>(
library: &Library,
(reference, on, as_of): (&str, Option<Day>, Option<Moment>),
json: bool,
environment: &E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (space, entity) = library.locate_or_deleted(reference)?;
let Some(diff) = library.revision_diff(space, entity, false)? else {
return show_entity(
library,
(space, entity),
(reference, on, as_of),
json,
environment,
output,
);
};
let mut shown = Vec::new();
let what = (reference, on, as_of);
show_entity(
library,
(space, entity),
what,
json,
environment,
&mut shown,
)?;
if json {
let mut value: serde_json::Value = serde_json::from_slice(&shown)
.map_err(|error| CliError::Io(io::Error::other(error)))?;
value["diff"] = trees::diff_json(&diff);
return output::print_json(&value, output);
}
output.write_all(&shown)?;
writeln!(output)?;
trees::diff_text(&diff, output)
}
fn show_entity<E: Environment>(
library: &Library,
(space, entity): (SpaceId, EntityId),
(reference, on, as_of): (&str, Option<Day>, Option<Moment>),
json: bool,
environment: &E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let Some(as_of) = as_of else {
let day = dating(environment, environment.now(), on).day;
return show(library, space, entity, When::given(day, on), json, output);
};
let zone = environment.time_zone();
let (millis, as_of_day) = as_of.resolve(&zone)?;
let when = When {
day: on.unwrap_or(as_of_day),
as_of: millis,
given: Some(on.unwrap_or(as_of_day)),
};
let recorded = match millis {
Some(millis) => library
.entity_as_of(space, entity, when.day, millis)?
.is_some(),
None => false,
};
if !recorded {
return Err(CliError::NotYet {
entity: reference.to_owned(),
when: millis.map_or_else(
|| "1970".to_owned(),
|millis| output::moment_text(millis, &zone),
),
});
}
show(library, space, entity, when, json, output)
}
fn reading_command<E: Environment>(
library: &Library,
cli: &Cli,
library_folder: &Path,
environment: &E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
match &cli.command {
Command::Status { .. } => {
let mut checkouts = Vec::new();
for space in library.spaces() {
checkouts.extend(library.checkouts(space)?);
}
let checks = library
.sync_records(UnwrapErr(SysRng))
.ok()
.and_then(|records| library.check_status(&records, environment.now()).ok());
let name_of = |space, file: Option<EntityId>| match file {
Some(file) => library.name(space, file).ok().flatten(),
None => library.space_name(space).ok().flatten(),
};
let zone = environment.time_zone();
let checks = output::Checks {
status: checks.as_ref(),
name_of: &name_of,
zone: &zone,
};
let mut thumbnails = std::collections::BTreeMap::new();
for space in library.spaces() {
thumbnails.insert(space, library.thumbnail_counts(space)?);
}
output::status(
(&library.status()?, &checkouts, &thumbnails),
checks,
library_folder,
json,
output,
)
}
Command::Show { entity, on, as_of } => {
show_command(library, (entity, *on, *as_of), json, environment, output)
}
Command::History { entity, field } => history_command(
library,
(entity, field.as_deref()),
json,
environment,
output,
),
Command::Export { folder, current } => {
export_command(library, folder, *current, json, output)
}
Command::Find { words, all } => {
let words = words.join(" ");
let first = if *all { usize::MAX } else { FIND_FIRST };
let mut groups = Vec::new();
for space in spaces_to_read(library) {
let found = library.search_first(space, &words, first, |entity, _| {
Ok(library.moved_into(space, entity)?.is_none())
})?;
groups.push((library.space_name(space)?, found));
}
let missed = not_looked_in(library)?;
output::found_in_spaces((&groups, &missed), json, output)
}
Command::List {
kind,
conditions,
sort,
on,
} => {
let list = (kind.as_deref(), conditions.as_slice(), sort.as_deref());
list_command(library, list, *on, json, environment, output)
}
_ => unreachable!("only commands that read come here"),
}
}
fn export_command(
library: &Library,
folder: &Path,
current: bool,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let kind = if current {
nibkeep_node::ExportKind::Current
} else {
nibkeep_node::ExportKind::Full
};
let exported = library.export(library.default_space(), folder, kind)?;
output::exported(&exported, folder, kind, json, output)
}
fn verify_export_command(
library: &Library,
folder: &Path,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let check = library.verify_export(folder)?;
output::export_check(&check, folder, json, output)?;
match check.problems.len() {
0 => Ok(()),
problems => Err(CliError::UnsoundExport(problems)),
}
}
fn verify_command<E: Environment>(
library: &mut Library,
export: Option<&Path>,
json: bool,
environment: &E,
output: &mut dyn Write,
) -> Result<(), CliError> {
if let Some(folder) = export {
return verify_export_command(library, folder, json, output);
}
let report = library.verify(environment.now())?;
let set_aside = report.spaces.iter().any(|space| {
space
.problems
.iter()
.any(|problem| matches!(problem, nibkeep_node::Problem::DamagedBlob(_)))
});
if set_aside && let Ok(records) = library.sync_records(UnwrapErr(SysRng)) {
let _ = records.ask(None, environment.now());
}
output::report(&report, json, output)?;
let problems = report.problems();
if problems > 0 {
return Err(CliError::Unsound(problems));
}
Ok(())
}
fn list_command<E: Environment>(
library: &Library,
list: (Option<&str>, &[String], Option<&str>),
on: Option<Day>,
json: bool,
environment: &E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let mut groups = Vec::new();
let mut failed = None;
for space in spaces_to_read(library) {
match listed_in(library, space, list, on, environment) {
Ok(listed) => groups.push((space, listed)),
Err(
error @ (CliError::NoType(_)
| CliError::AmbiguousType { .. }
| CliError::NoField { .. }
| CliError::AmbiguousField { .. }),
) => {
failed = failed.or(Some(error));
}
Err(error) => return Err(error),
}
}
if groups.is_empty()
&& let Some(error) = failed
{
return Err(error);
}
let missed = not_looked_in(library)?;
output::entities_in_spaces((&named_groups(library, groups)?, &missed), json, output)
}
fn not_looked_in(library: &Library) -> Result<Vec<String>, CliError> {
if library.chosen_space().is_some() {
return Ok(Vec::new());
}
let looked_in = library.spaces();
Ok(library
.known_spaces()?
.into_iter()
.filter(|known| !looked_in.contains(&known.space))
.map(|known| known.name.unwrap_or_else(|| known.space.to_string()))
.collect())
}
fn spaces_to_read(library: &Library) -> Vec<nibkeep_base::SpaceId> {
match library.chosen_space() {
Some(space) => vec![space],
None => library.spaces(),
}
}
const FIND_FIRST: usize = 50;
type NamedGroup = (Option<String>, Vec<nibkeep_node::Listed>);
fn named_groups(
library: &Library,
groups: Vec<(nibkeep_base::SpaceId, Vec<nibkeep_node::Listed>)>,
) -> Result<Vec<NamedGroup>, CliError> {
groups
.into_iter()
.map(|(space, listed)| {
let mut kept = Vec::new();
for entity in listed {
if library.moved_into(space, entity.id)?.is_none() {
kept.push(entity);
}
}
Ok((library.space_name(space)?, kept))
})
.collect()
}
fn listed_in<E: Environment>(
library: &Library,
space: nibkeep_base::SpaceId,
(kind, conditions, sort): (Option<&str>, &[String], Option<&str>),
on: Option<Day>,
environment: &E,
) -> Result<Vec<nibkeep_node::Listed>, CliError> {
let types = library.types(space)?;
let kind = match kind {
Some(kind) => Some(types::type_named(kind, &types)?),
None => None,
};
let mut held: Option<Vec<TypeName>> = None;
let mut field_named = |text: &str| -> Result<FieldName, CliError> {
let Some(kind) = &kind else {
let every: Vec<TypeName> = types
.iter()
.map(|definition| definition.name().clone())
.collect();
return types::field_named(text, &types, &every);
};
types::field_of_listed(text, &types, kind, || {
if held.is_none() {
held = Some(library.types_with(space, kind)?.into_iter().collect());
}
Ok(held.as_deref().unwrap_or_default())
})
};
let mut conditions_given = Vec::new();
for condition in conditions {
let (field, text) = condition
.split_once('=')
.filter(|(_, text)| !text.is_empty())
.ok_or_else(|| CliError::Assignment(condition.clone()))?;
let field = field_named(field)?;
if is_secret(library, space, &field) {
return Err(CliError::SecretField(field));
}
let value = types::value(text, &field, &types, library, space)?;
conditions_given.push((field, value));
}
let order_by = match sort {
Some(field) => {
let field = field_named(field)?;
if is_secret(library, space, &field) {
return Err(CliError::SecretField(field));
}
Some(field)
}
None => None,
};
let listing = nibkeep_node::Listing {
of_type: kind,
conditions: conditions_given,
order_by,
on,
};
let today = dating(environment, environment.now(), None).day;
Ok(library.list(space, &listing, today)?)
}
fn merge_command<E: Environment>(
library: &mut Library,
(reference, other, undo): (&str, Option<&str>, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (space, found) = library.locate(reference)?;
library.choose_space(Some(space))?;
let now = environment.now();
let shown = if undo {
let member = match other {
Some(other) => match library.find_merged(space, found, other) {
Err(NodeError::NotMerged(_)) if library.merged(space, found)?.is_empty() => {
return Err(CliError::NothingMerged(reference.to_owned()));
}
Err(NodeError::NotMerged(_)) => {
return Err(CliError::NotMergedInto {
entity: reference.to_owned(),
other: other.to_owned(),
});
}
found => found?,
},
None => match library.merged(space, found)?.as_slice() {
[] => return Err(CliError::NothingMerged(reference.to_owned())),
[only] => only.id,
merged => {
return Err(CliError::WhichMerged {
entity: reference.to_owned(),
candidates: output::listed_names(merged),
});
}
},
};
library.undo_merge(space, member, now, environment.rng())?;
member
} else {
let from = match library.find_merged(space, found, reference) {
Ok(member) => member,
Err(NodeError::NotMerged(_)) => found,
Err(error) => return Err(error.into()),
};
let other = other.unwrap_or_default();
let into = library.find_entity(space, other)?;
library
.merge_entities(space, from, into, now, environment.rng())
.map_err(|error| match error {
NodeError::SameEntity(_) => CliError::OneAlready {
entity: reference.to_owned(),
into: other.to_owned(),
},
error => error.into(),
})?;
into
};
let day = dating(environment, now, None).day;
show(library, space, shown, When::on(day), json, output)
}
fn history_command<E: Environment>(
library: &Library,
(reference, field): (&str, Option<&str>),
json: bool,
environment: &E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (space, entity) = library.locate_or_deleted(reference)?;
let mut history = library
.history(space, entity, None)?
.ok_or_else(|| NodeError::NoEntity(entity.to_string()))?;
if let Some(field) = field {
let had: Vec<_> = history
.fields
.iter()
.map(|past| past.field.clone())
.collect();
let wanted = types::field_among(field, &had).map_err(|error| {
let day = dating(environment, environment.now(), None).day;
let view = library.entity(space, entity, day).ok().flatten();
let types = library.types(space).ok();
let secret = types
.zip(view)
.and_then(|(types, view)| types::field_named(field, &types, &view.types).ok())
.filter(|field| is_secret(library, space, field));
secret.map_or(error, CliError::SecretHistory)
})?;
history.fields.retain(|past| past.field == wanted);
}
let name_of = |entity| library.name(space, entity).ok().flatten();
output::history(&history, &name_of, &environment.time_zone(), json, output)
}
fn new_command<E: Environment>(
library: &mut Library,
(kind, values, language): (&str, &[String], Option<&Tag>),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let types = library.types(space)?;
let mut kinds: Vec<TypeName> = Vec::new();
for name in kind.split(',') {
let name = types::type_named(name.trim(), &types)?;
if nibkeep_node::OWN_RECORDS.contains(&name) {
return Err(NodeError::OwnType(name).into());
}
if !kinds.contains(&name) {
kinds.push(name);
}
}
let mut parsed = Vec::new();
for assignment in values {
let (field, text) = assignment
.split_once('=')
.ok_or_else(|| CliError::Assignment(assignment.clone()))?;
let field = types::field_named(field, &types, &kinds)?;
if is_secret(library, space, &field) {
return Err(CliError::SecretField(field));
}
let value = types::value(text, &field, &types, library, space)?;
parsed.push((field, value));
}
let recorded_before = library.same_relationship(space, &kinds, &parsed)?;
let now = environment.now();
let rng = environment.rng();
let entity = match language {
Some(language) => {
library.create_entity_with_language(space, &kinds, parsed, language, now, rng)?
}
None => library.create_entity(space, &kinds, parsed, now, rng)?,
};
let day = dating(environment, now, None).day;
show_added(
library,
space,
entity,
&recorded_before,
When::on(day),
json,
output,
)
}
fn languages_command<E: Environment>(
library: &mut Library,
command: &Command,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let Command::Languages {
ranges,
device,
app,
clear,
} = command
else {
unreachable!("only for nib languages");
};
let whose = match (device, app) {
(true, _) => LanguagesFor::Device,
(_, true) => LanguagesFor::Replica,
_ => LanguagesFor::User,
};
let set = match ranges {
Some(ranges) => Some(Some(ranges.parse::<Languages>()?)),
None if *clear => Some(None),
None => None,
};
if let Some(languages) = set {
let now = environment.now();
library.set_languages(whose, languages.as_ref(), now, environment.rng())?;
}
output::languages(&library.language_settings()?, json, output)
}
fn edit_command<E: Environment>(
library: &mut Library,
arguments: &EditArgs,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let EditArgs {
entity,
changes,
date,
on,
delete,
restore,
language,
form,
form_of,
} = arguments;
let (space, id) = library.locate_or_deleted(entity)?;
library.choose_space(Some(space))?;
let now = environment.now();
let mut dating = dating(environment, now, *on);
if let Some(date) = date {
dating = dating.with_valid_time(date.clone());
}
if let Some(language) = language {
dating = dating.with_language(language.clone());
}
let view = library
.entity(space, id, dating.day)?
.ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
let forms = match (form_of, form) {
(Some(of), _) => Forms::Of(of),
(None, true) => Forms::OfTheOnly,
(None, false) => Forms::No,
};
let mut edits = edits(changes, forms, &view, library, space)?;
if *delete {
edits.push(Edit::Delete);
}
if *restore {
edits.push(Edit::Restore);
}
library.edit_entity(space, id, edits, &dating, now, environment.rng())?;
show(
library,
space,
id,
When::given(dating.day, *on),
json,
output,
)
}
fn purge_command<E: Environment>(
library: &mut Library,
(entity, assignment, confirmed): (&str, &str, bool),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (space, id) = library.locate_or_deleted(entity)?;
library.choose_space(Some(space))?;
let view = library
.entity(space, id, dating(environment, environment.now(), None).day)?
.ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
let (field, text) = assignment
.split_once('=')
.ok_or_else(|| CliError::Assignment(assignment.to_owned()))?;
let types = library.types(space)?;
let field = types::field_named(field, &types, &view.types)?;
let secret = is_secret(library, space, &field);
if secret && !text.is_empty() {
return Err(CliError::SecretGiven(field));
}
let value = if text.is_empty() {
None
} else {
Some(types::value(text, &field, &types, library, space)?)
};
if secret && library.secrets_protection()?.is_some() {
unlock_secrets(library, false, environment, timings)?;
}
let purged = purge_values(
library,
(id, &field, value.as_ref()),
confirmed,
environment,
);
library.lock_secrets();
let purged = purged?;
let name_of = |entity| library.name(space, entity).ok().flatten();
let elsewhere = space_names(library, &purged.elsewhere);
output::purge(
&purged,
(&field, &name_of),
&elsewhere,
confirmed,
json,
output,
)?;
if confirmed {
Ok(())
} else {
Err(CliError::Unconfirmed)
}
}
fn purges_waiting_command<E: Environment>(
library: &mut Library,
command: Option<&PurgesCommand>,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let zone = environment.time_zone();
let records = library.sync_records(UnwrapErr(SysRng))?;
let remembered: BTreeMap<EntityId, PathBuf> = records
.backup_folders()?
.into_iter()
.map(|(backup, found)| (backup, found.folder))
.collect();
let found = library.find_backups(&remembered)?;
let Some(command) = command else {
let mut waiting = library.waiting_purges()?;
waiting.extend(library.waiting_purges_on(&found)?);
let mut spaces = Vec::new();
for purge in &waiting {
spaces.push(space_display_name(library, purge.space)?);
}
let days = library.own_wait_days()?;
return output::waiting_purges((&waiting, &spaces), days, &zone, json, output);
};
let (name, on, yes, stopping) = match command {
PurgesCommand::Stop { purge, on, yes } => (purge, on, *yes, true),
PurgesCommand::End { purge, on, yes } => (purge, on, *yes, false),
};
let waiting = library.find_waiting_purges(name, (&found, on.as_deref()))?;
let space = space_display_name(library, waiting[0].space)?;
if yes {
let now = environment.now();
let updated = if stopping {
library.stop_purge(&waiting, now, environment.rng())?
} else {
library.end_wait(&waiting, now)?.1
};
let kept = library.changes_kept()?;
for backup in updated {
if let Some(on) = waiting
.iter()
.filter_map(|place| place.on.as_ref())
.find(|on| on.backup == backup.id)
{
records.record_backup(on.backup, &on.folder, Some((now, kept)))?;
}
}
}
output::purge_waited((&waiting, &space), (stopping, yes), &zone, json, output)?;
if yes {
Ok(())
} else {
Err(CliError::Unconfirmed)
}
}
fn move_command<E: Environment>(
library: &mut Library,
((entity, to, without_history, confirmed), (keep_behind, leave_secrets)): (
(&str, &str, bool, bool),
(bool, bool),
),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (from, found) = library.locate(entity)?;
let to = library.find_space(to)?;
let preview = library.move_preview(from, found, to)?;
let name = |space: nibkeep_base::SpaceId| -> Result<String, CliError> {
Ok(library
.space_name(space)?
.unwrap_or_else(|| space.to_string()))
};
let (from_name, to_name) = (name(from)?, name(to)?);
let others = !preview.losing.is_empty() || !preview.gaining.is_empty();
if (preview.entities.len() > 1 || !preview.staying.is_empty() || others) && !confirmed {
let name_of = |entity| library.name(from, entity).ok().flatten();
output::move_preview(&preview, (&from_name, &to_name), &name_of, json, output)?;
return Err(CliError::UnconfirmedMove);
}
let history = if without_history {
MoveHistory::Leave
} else {
MoveHistory::Bring
};
let behind = if keep_behind {
nibkeep_node::Behind::Keep
} else {
nibkeep_node::Behind::Purge
};
let secrets = if leave_secrets {
MoveSecrets::Leave
} else {
MoveSecrets::Bring
};
if preview.secrets && !leave_secrets && library.secrets_protection()?.is_some() {
unlock_secrets(library, false, environment, timings)?;
}
let now = environment.now();
let moved = library.move_entity(
from,
found,
to,
history,
behind,
secrets,
now,
environment.rng(),
);
library.lock_secrets();
let moved = moved?;
output::moved(moved, preview.entities.len(), &to_name, json, output)?;
output::seen_first(
&preview.gaining,
history == MoveHistory::Bring,
json,
output,
)?;
if behind == nibkeep_node::Behind::Purge {
output::purged_later(&preview, &from_name, json, output)?;
}
Ok(())
}
fn purge_either<E: Environment>(
library: &mut Library,
(entity, value, confirmed): (&str, Option<&str>, bool),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
match value {
Some(value) => purge_command(
library,
(entity, value, confirmed),
json,
environment,
timings,
output,
),
None => purge_behind_command(
library,
(entity, confirmed),
json,
environment,
timings,
output,
),
}
}
fn purge_behind_command<E: Environment>(
library: &mut Library,
(entity, confirmed): (&str, bool),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let mut asked = None;
for space in library.spaces() {
if let Ok(found) = library.find_entity_or_deleted(space, entity)
&& library.behind(space, found)?.is_some()
{
asked = Some((space, found));
break;
}
}
let Some((space, found)) = asked else {
return Err(NodeError::NoPurgeAsked(entity.to_owned()).into());
};
let mut secret = library.may_hold_secrets(space, found)?;
if let Some((there, now)) = library.moved_into(space, found)? {
secret |= library.may_hold_secrets(there, now)?;
}
if secret && library.secrets_protection()?.is_some() {
unlock_secrets(library, false, environment, timings)?;
}
let purged = purge_behind_found(
library,
(space, found, confirmed),
json,
environment,
output,
);
library.lock_secrets();
purged
}
fn purge_behind_found<E: Environment>(
library: &mut Library,
(space, found, confirmed): (nibkeep_base::SpaceId, nibkeep_base::EntityId, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let remaining = library.behind(space, found)?.unwrap_or_default();
if !confirmed && remaining > 0 {
output::purge_behind(remaining, false, json, output)?;
return Err(CliError::Unconfirmed);
}
let now = environment.now();
let purged = library.purge_behind(space, found, now, environment.rng())?;
output::purge_behind(purged, true, json, output)
}
fn space_names(library: &Library, spaces: &[nibkeep_base::SpaceId]) -> Vec<String> {
spaces
.iter()
.map(|&space| {
library
.space_name(space)
.ok()
.flatten()
.unwrap_or_else(|| space.to_string())
})
.collect()
}
fn sorted_space_names(library: &Library, spaces: &[nibkeep_base::SpaceId]) -> Vec<String> {
let mut names = space_names(library, spaces);
names.sort();
names
}
fn purge_values<E: Environment>(
library: &mut Library,
(entity, field, value): (
nibkeep_base::EntityId,
&FieldName,
Option<&nibkeep_model::Value>,
),
confirmed: bool,
environment: &mut E,
) -> Result<nibkeep_node::Purge, NodeError> {
let space = library.default_space();
if confirmed {
let now = environment.now();
library.purge(space, entity, field, value, now, environment.rng())
} else {
library.purgeable(space, entity, field, value)
}
}
fn takeout_command<E: Environment>(
library: &mut Library,
(parts, from): (&[PathBuf], Option<&str>),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let takeout = nibkeep_import::Takeout::open(parts).map_err(import_error)?;
let started = environment.now();
let began = std::time::Instant::now();
let now = move || started + u64::try_from(began.elapsed().as_millis()).unwrap_or(0);
library.install_policies(
space,
environment.downloads().as_deref(),
now(),
environment.rng(),
)?;
let mut found = output::FilesAdded::default();
let mut pictures = Vec::new();
let mut thumbnails_rng = UnwrapErr(SysRng);
let source = from.unwrap_or(nibkeep_import::GOOGLE_PHOTOS);
let report = takeout
.import(
library,
(space, source),
&now,
environment.rng(),
&mut |library, imported| {
if let Some(added) = &imported.added
&& !added.known
{
pictures.push(added.content);
}
if pictures.len() >= THUMBNAIL_ROUND {
thumbnails_of(
library,
(space, &mut pictures),
&mut found,
(now(), &mut thumbnails_rng),
);
}
Ok(())
},
)
.map_err(import_error)?;
thumbnails_of(
library,
(space, &mut pictures),
&mut found,
(now(), &mut thumbnails_rng),
);
output::takeout_imported((&report, source), &found, json, output)?;
match report.failed.len() {
0 => Ok(()),
failed => Err(CliError::FilesFailed(failed)),
}
}
fn import_error(error: nibkeep_import::ImportError) -> CliError {
match error {
nibkeep_import::ImportError::Node(error) => error.into(),
other => CliError::Import(other.to_string()),
}
}
fn path_in_source(given: &[PathBuf], file: &Path) -> Option<String> {
let root = given.iter().find(|given| file.starts_with(given))?;
let base = root.parent().unwrap_or(Path::new(""));
let within = file.strip_prefix(base).ok()?;
let names: Vec<String> = within
.components()
.filter_map(|part| match part {
std::path::Component::Normal(name) => Some(name.to_string_lossy().into_owned()),
_ => None,
})
.collect();
(!names.is_empty()).then(|| names.join("/"))
}
fn file_add_command<E: Environment>(
library: &mut Library,
(paths, own, from): (&[PathBuf], &Path, Option<&str>),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let source = match from {
Some(name) => {
let now = environment.now();
Some(library.source_named(space, name, now, environment.rng())?)
}
None => None,
};
let mut found = output::FilesAdded::default();
let mut files = Vec::new();
let own = std::fs::canonicalize(own).unwrap_or_else(|_| own.to_owned());
for path in paths {
gather(path, (true, &own), &mut files, &mut found);
}
if !json {
for (path, reason) in &found.failed {
output::file_failed(path, reason, output)?;
}
}
let downloads = environment.downloads();
let now = environment.now();
library.install_policies(space, downloads.as_deref(), now, environment.rng())?;
let mut pictures = Vec::new();
for path in files {
if pictures.len() >= THUMBNAIL_ROUND {
thumbnail_round(library, (space, &mut pictures), &mut found, environment);
}
if !json && let Ok(Some(question)) = library.question_for(space, &path) {
let asked = environment.ask(&output::question(&path, &question))?;
let answer = asked.and_then(|answer| match answer.to_lowercase().as_str() {
"y" | "yes" => Some(true),
"n" | "no" => Some(false),
_ => None,
});
if let Some(again) = answer {
let now = environment.now();
library.answer(space, &question, again, now, environment.rng())?;
}
}
let now = environment.now();
let from = nibkeep_node::FileFrom {
source,
source_path: source.and_then(|_| path_in_source(paths, &path)),
..nibkeep_node::FileFrom::default()
};
match library.add_file_from(space, &path, &from, now, environment.rng()) {
Ok(added) => {
if !json {
let name_of = |entity| library.name(space, entity).ok().flatten();
output::file_added(&path, &added, &name_of, output)?;
}
if !added.known {
pictures.push(added.content);
}
found.added.push((path, added));
}
Err(NodeError::Unreadable { reason, .. }) => {
if !json {
output::file_failed(&path, &reason, output)?;
}
found.failed.push((path, reason));
}
Err(NodeError::CheckedOut(_) | NodeError::InTree(_)) if !paths.contains(&path) => {
found.left_out += 1;
}
Err(error @ (NodeError::CheckedOut(_) | NodeError::InTree(_))) => {
let reason = if matches!(error, NodeError::InTree(_)) {
"in a tree; nib commit records it"
} else {
"a checkout; nib file checkin records its edits"
};
if !json {
output::file_failed(&path, reason, output)?;
}
found.failed.push((path, reason.to_owned()));
}
Err(error) => {
thumbnail_round(library, (space, &mut pictures), &mut found, environment);
output::files_added(&found, json, output)?;
return Err(error.into());
}
}
}
thumbnail_round(library, (space, &mut pictures), &mut found, environment);
output::files_added(&found, json, output)?;
match found.failed.len() {
0 => Ok(()),
failed => Err(CliError::FilesFailed(failed)),
}
}
fn thumbnail_round<E: Environment>(
library: &mut Library,
(space, pictures): (SpaceId, &mut Vec<nibkeep_base::Hash>),
found: &mut output::FilesAdded,
environment: &mut E,
) {
let now = environment.now();
thumbnails_of(library, (space, pictures), found, (now, environment.rng()));
}
fn thumbnails_of(
library: &mut Library,
(space, pictures): (SpaceId, &mut Vec<nibkeep_base::Hash>),
found: &mut output::FilesAdded,
(now, rng): (u64, &mut impl getrandom::rand_core::CryptoRng),
) {
if found.thumbnails_failed.is_none() && !pictures.is_empty() {
match library.make_thumbnails(space, pictures, now, rng) {
Ok(made) => found.thumbnails += made,
Err(error) => found.thumbnails_failed = Some(error.to_string()),
}
}
pictures.clear();
}
fn file_command<E: Environment>(
library: &mut Library,
(command, folder): (&FileCommand, &Path),
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
match command {
FileCommand::Add {
paths,
secret: true,
to,
..
} => {
let added =
secret_file_add_command(library, (paths, to), json, environment, timings, output);
library.lock_secrets();
added
}
FileCommand::Add { paths, from, .. } => {
let own = folder.join(LIBRARY_DATA);
let added = (paths.as_slice(), &*own, from.as_deref());
file_add_command(library, added, json, environment, output)
}
FileCommand::Checkout { file, path } => {
let checkout = (file.as_str(), path.as_deref());
file_checkout_command(library, checkout, cli, environment, output)
}
FileCommand::Pin { file, device } | FileCommand::Unpin { file, device } => {
let pinned = matches!(command, FileCommand::Pin { .. });
let (space, file) = library.locate(file)?;
let (device, device_name) = if let Some(device) = device {
one_device(library, device)?
} else {
let this = library.replicas()?.into_iter().find(|replica| replica.this);
(
this.as_ref()
.and_then(|replica| replica.device)
.ok_or_else(|| NodeError::WhichDevice("this device".to_owned()))?,
this.and_then(|replica| replica.device_name),
)
};
let now = environment.now();
library.pin_file((space, file), device, pinned, now, environment.rng())?;
let name = library.name(space, file)?;
output::pinned(
(file, name.as_deref()),
(device, device_name.as_deref()),
pinned,
json,
output,
)
}
FileCommand::Checkin { copy, keep, force } => {
let checkin = (copy.as_str(), *keep, *force);
file_checkin_command(library, checkin, json, environment, output)
}
FileCommand::Where { file } => {
let (space, file) = library.locate(file)?;
let copies = library.copies_of(space, file, environment.now())?;
let name = library.name(space, file)?;
let zone = environment.time_zone();
output::file_copies((&copies, name.as_deref()), &zone, json, output)
}
FileCommand::Thumbnail { file, path } => {
let (space, file) = library.locate(file)?;
let path = absolute(path, environment)?;
let thumbnail = library
.thumbnail(space, file)?
.ok_or_else(|| CliError::NoThumbnail(file.to_string()))?;
match library.save_thumbnail(space, &thumbnail, &path) {
Err(NodeError::PlaceTaken(path)) => return Err(CliError::Exists(path)),
saved => saved?,
}
output::thumbnail_written(&thumbnail, &path, json, output)
}
FileCommand::Thumbnails => {
let space = library.default_space();
let now = environment.now();
let mut progress = |made: nibkeep_node::ThumbnailsMade, of: usize| {
let done = made.made + made.unreadable + made.not_here;
if of > THUMBNAIL_ROUND && done < of {
let _ = output::progress(&format!("{done} of {of} pictures…"), json, output);
}
};
let made = library.make_missing_thumbnails(
space,
THUMBNAIL_ROUND,
now,
environment.rng(),
&mut progress,
)?;
let left = library.missing_thumbnails(space)?.len();
output::thumbnails_made(made, left, json, output)
}
}
}
const THUMBNAIL_ROUND: usize = 64;
struct RustDecoders;
impl nibkeep_node::Thumbnailer for RustDecoders {
fn made_with(&self) -> &str {
nibkeep_thumbnails::MADE_WITH
}
fn reads(&self, media_type: &str) -> bool {
nibkeep_thumbnails::reads(media_type)
}
fn make(&self, picture: &[u8]) -> Option<nibkeep_node::Thumbnail> {
let made = nibkeep_thumbnails::make(picture).ok()?;
Some(nibkeep_node::Thumbnail {
jpeg: made.jpeg,
width: made.width,
height: made.height,
picture_hash: Some(made.picture_hash),
})
}
}
fn file_checkout_command<E: Environment>(
library: &mut Library,
(file, place): (&str, Option<&Path>),
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
let (space, file) = library.locate(file)?;
library.choose_space(Some(space))?;
let place = match place {
Some(place) => absolute(place, environment)?,
None => current_dir(environment)?,
};
let now = environment.now();
let checked_out = match library.checkout(space, file, &place, now, environment.rng()) {
Err(NodeError::SecretFile(name)) => return Err(CliError::SecretFileCheckout(name)),
Err(NodeError::NoCopyHere(name)) => {
let (holders, reached) = fetch((space, file), library, cli, environment, output)?;
let now = environment.now();
match library.checkout(space, file, &place, now, environment.rng()) {
Err(NodeError::NoCopyHere(_)) if !reached.is_empty() => {
return Err(CliError::NotGiven {
name,
holders: reached,
});
}
Err(NodeError::NoCopyHere(_)) if !holders.is_empty() => {
return Err(CliError::NotFetched { name, holders });
}
checked_out => checked_out?,
}
}
checked_out => checked_out?,
};
let name = library.name(space, checked_out.file)?;
output::checked_out(&checked_out, name.as_deref(), json, output)
}
const FETCH_WAIT: Duration = Duration::from_secs(10);
fn fetch<E: Environment>(
(space, file): (nibkeep_base::SpaceId, EntityId),
library: &mut Library,
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(Vec<String>, Vec<String>), CliError> {
let holders = library.holders_of(space, file)?;
let name_of = |replica: &nibkeep_node::Replica| {
let app = replica.name.clone().unwrap_or_else(|| "nib".to_owned());
match &replica.device_name {
Some(device) => format!("{app} on {device}"),
None => app,
}
};
let names: Vec<String> = holders.iter().map(name_of).collect();
if holders.is_empty() {
return Ok((names, Vec::new()));
}
output::progress(
&format!("Fetching it from {}…", names.join(", ")),
cli.json,
output,
)?;
let waited = Instant::now();
let _role = loop {
if let Some(role) = library.take_role()? {
break role;
}
let records = library.sync_records(UnwrapErr(SysRng))?;
if let Some(holder) = records.holder()? {
let asked = environment.now();
let asks = holders
.iter()
.map(|replica| records.ask(Some(replica.id), asked))
.collect::<Result<Vec<_>, _>>()?;
let mut released = false;
while !released
&& asks
.iter()
.any(|ask| matches!(records.answered(*ask), Ok(None)))
{
if library.take_role()?.is_some() {
released = true;
} else if waited.elapsed() > FETCH_WAIT + ASK_WAIT {
return Err(CliError::NotAnswered(holder.program));
} else {
std::thread::sleep(Duration::from_millis(100));
}
}
if !released {
library.catch_up()?;
let synced = records.synced_since(asked)?;
let reached = holders
.iter()
.filter(|replica| synced.contains_key(&replica.id))
.map(name_of)
.collect();
return Ok((names, reached));
}
continue;
}
if waited.elapsed() > FETCH_WAIT + ASK_WAIT {
return Err(CliError::NotAnswered("another program".to_owned()));
}
std::thread::sleep(Duration::from_millis(100));
};
let network = library.network(cli.network(false))?;
let endpoints = holders
.iter()
.filter_map(|replica| replica.endpoint)
.collect();
let found = network.find(&endpoints, FETCH_WAIT);
let now = clock(environment);
let synced =
nibkeep_node::sync_with_found(library, &network, holders, &found, &now, environment.rng());
let reached = synced
.iter()
.filter(|with| with.synced.is_ok())
.map(|with| name_of(&with.replica))
.collect();
Ok((names, reached))
}
fn one_device(library: &Library, device: &str) -> Result<(EntityId, Option<String>), CliError> {
let replicas = library.replicas_named(device)?;
let devices: std::collections::BTreeSet<EntityId> = replicas
.iter()
.filter_map(|replica| replica.device)
.collect();
let mut found = devices.into_iter();
let (Some(chosen), None) = (found.next(), found.next()) else {
return Err(NodeError::WhichDevice(format!(
"{device} names no one device of yours; nib device list shows them"
))
.into());
};
let name = replicas
.iter()
.find(|replica| replica.device == Some(chosen))
.and_then(|replica| replica.device_name.clone());
Ok((chosen, name))
}
fn devices_named(library: &Library, devices: &[String]) -> Result<Vec<EntityId>, CliError> {
let mut records = Vec::new();
for device in devices {
let named: Vec<EntityId> = library
.replicas_named(device)?
.into_iter()
.filter(|replica| !replica.revoked && !replica.ai_agent && !replica.this)
.map(|replica| replica.id)
.collect();
if named.is_empty() {
return Err(NodeError::WhichDevice(format!(
"{device} names no other device of yours; nib device list shows them"
))
.into());
}
records.extend(named);
}
Ok(records)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Keeps(Option<u64>);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Waits(Option<u64>);
fn parse_waits(text: &str) -> Result<Waits, String> {
let text = text.trim().to_ascii_lowercase();
match text.as_str() {
"default" => return Ok(Waits(None)),
"none" | "0" => return Ok(Waits(Some(0))),
_ => {}
}
let digits = text
.strip_suffix("days")
.or_else(|| text.strip_suffix("day"))
.or_else(|| text.strip_suffix('d'))
.unwrap_or(&text)
.trim();
match digits.parse::<u64>() {
Ok(days @ 1..=nibkeep_node::MOST_WAIT_DAYS) => Ok(Waits(Some(days))),
_ => Err("days from 1 to 365, such as 30, or none, or default".to_owned()),
}
}
fn parse_keeps(text: &str) -> Result<Keeps, String> {
if text.trim().eq_ignore_ascii_case("default") {
return Ok(Keeps(None));
}
parse_size(text).map(|size| Keeps(Some(size)))
}
fn secret_file_add_command<E: Environment>(
library: &mut Library,
(paths, to): (&[PathBuf], &[String]),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let mut attached_to = Vec::with_capacity(to.len());
for entity in to {
attached_to.push(library.find_entity(space, entity)?);
}
let mut files = Vec::with_capacity(paths.len());
for path in paths {
let path = absolute(path, environment)?;
if path.is_dir() {
return Err(CliError::SecretFolder(path));
}
files.push(path);
}
unlock_secrets(library, true, environment, timings)?;
let mut added = Vec::with_capacity(files.len());
let mut failed = Vec::new();
for path in files {
let file = match std::fs::File::open(&path) {
Ok(file) => file,
Err(error) => {
if !json {
output::file_failed(&path, &error.to_string(), output)?;
}
failed.push((path, error.to_string()));
continue;
}
};
let name = path
.file_name()
.map_or_default(|name| name.to_string_lossy().into_owned());
let now = environment.now();
let secret_file =
match library.add_secret_file(space, &name, file, &attached_to, now, environment.rng())
{
Ok(secret_file) => secret_file,
Err(NodeError::Unreadable { reason, .. }) => {
if !json {
output::file_failed(&path, &reason, output)?;
}
failed.push((path, reason));
continue;
}
Err(error) => return Err(error.into()),
};
if !json {
let name_of = |entity| library.name(space, entity).ok().flatten();
output::secret_file_added(&path, &secret_file, (&attached_to, &name_of), output)?;
}
added.push((path, name, secret_file));
}
output::secret_files_added((&added, &failed), &attached_to, json, output)?;
match failed.len() {
0 => Ok(()),
failed => Err(CliError::FilesFailed(failed)),
}
}
fn file_checkin_command<E: Environment>(
library: &mut Library,
(copy, keep, force): (&str, bool, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
if library.chosen_space().is_none() {
for space in library.spaces() {
library.choose_space(Some(space))?;
if find_checkout(library, copy, environment).is_ok() {
break;
}
library.choose_space(None)?;
}
}
let space = library.default_space();
let checkout = find_checkout(library, copy, environment)?;
let now = environment.now();
let recorded = match library.record_edits(space, checkout.id, force, now, environment.rng()) {
Err(NodeError::Stale(path)) => return Err(CliError::Stale(path)),
recorded => recorded?,
};
let ended = if keep {
None
} else {
let now = environment.now();
Some(library.end_checkout(space, checkout.id, now, environment.rng())?)
};
let mut thumbnail_failed = None;
if let Some(version) = recorded.version {
let now = environment.now();
if let Err(error) = library.make_thumbnails(space, &[version], now, environment.rng()) {
thumbnail_failed = Some(error.to_string());
}
}
let name = library.name(space, checkout.file)?;
let checked_in = output::CheckedIn {
checkout: &checkout,
recorded,
ended: ended.as_ref(),
name: name.as_deref(),
thumbnail_failed: thumbnail_failed.as_deref(),
};
output::checked_in(&checked_in, json, output)
}
fn find_checkout<E: Environment>(
library: &Library,
copy: &str,
environment: &E,
) -> Result<Checkout, CliError> {
let space = library.default_space();
let path = absolute(Path::new(copy), environment)?;
if let Some(checkout) = library.checkout_at(space, &path)? {
return Ok(checkout);
}
let file = match library.find_entity(space, copy) {
Ok(file) => file,
Err(NodeError::NoEntity(_)) => return Err(NodeError::NotCheckedOut(copy.to_owned()).into()),
Err(error) => return Err(error.into()),
};
let mut checkouts = library.checkouts_of(space, file)?;
match checkouts.len() {
0 => Err(NodeError::NotCheckedOut(copy.to_owned()).into()),
1 => Ok(checkouts.remove(0)),
_ => Err(NodeError::WhichCheckout {
file: copy.to_owned(),
paths: checkouts
.into_iter()
.map(|checkout| checkout.path)
.collect(),
}
.into()),
}
}
fn backup_edit<E: Environment>(
library: &mut Library,
command: &BackupCommand,
environment: &mut E,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let BackupCommand::Edit {
backup,
name,
spaces,
policies,
every_policy,
away,
home,
waits,
} = command
else {
unreachable!("backup_command passes only an edit");
};
let known = library.find_backup(backup)?;
let spaces = (!spaces.is_empty())
.then(|| {
spaces
.iter()
.map(|space| library.find_space(space))
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let of = spaces.clone().unwrap_or_else(|| known.spaces.clone());
let policies = if *every_policy {
Some(Vec::new())
} else if policies.is_empty() {
None
} else {
Some(backup_policies(library, &of, policies, environment)?)
};
let edit = BackupEdit {
name: name.clone(),
spaces,
policies,
away: (*away || *home).then_some(*away),
waits: waits.map(|Waits(days)| days),
};
let now = environment.now();
library.edit_backup(known.id, &edit, now, environment.rng())?;
let edited = library.find_backup(&known.id.to_string())?;
output::backup_edited(&edited, json, output)
}
fn safekeeping_command<E: Environment>(
library: &mut Library,
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
match &cli.command {
Command::Backup { command } => backup_command(library, command, cli, environment, output),
Command::Recovery { command } => {
recovery_command(library, command, cli.json, environment, timings, output)
}
_ => unreachable!("only nib backup and nib recovery come here"),
}
}
const CODE_TRIES: usize = 3;
fn typed_recovery_code<E: Environment>(
prompt: &str,
environment: &mut E,
json: bool,
output: &mut dyn Write,
) -> Result<RecoveryCode, CliError> {
for _ in 0..CODE_TRIES {
let typed = environment.passphrase(prompt)?;
match RecoveryCode::from_text(&typed) {
Ok(code) => return Ok(code),
Err(error) if !json => writeln!(output, "{error}.")?,
Err(_) => {}
}
}
Err(CliError::NotARecoveryCode)
}
fn recovery_new_command<E: Environment>(
library: &mut Library,
(secrets, revoke_older): (bool, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let code = RecoveryCode::generate(environment.rng());
output::recovery_shown(&code, json, output)?;
let mut stands = None;
for _ in 0..if json { 0 } else { CODE_TRIES } {
let prompt = "Type the code back, or press Enter to do it later: ";
let Ok(typed) = environment.passphrase(prompt) else {
break;
};
if typed.trim().is_empty() {
break;
}
match RecoveryCode::from_text(&typed) {
Ok(typed) if typed.same_as(&code) => {
let now = environment.now();
stands = Some(library.add_recovery_code(&code, secrets, now, environment.rng())?);
break;
}
Ok(_) => writeln!(output, "That is another code than the one shown.")?,
Err(error) => writeln!(output, "{error}.")?,
}
}
let replaced = if stands.is_some() {
let now = environment.now();
library.revoke_replaced_recovery_codes(revoke_older, now, environment.rng())?
} else {
Vec::new()
};
let codes = library.recovery_codes()?;
output::recovery_made(&code, stands.as_ref(), (&replaced, &codes), json, output)
}
fn recovery_command<E: Environment>(
library: &mut Library,
command: &RecoveryCommand,
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
const TYPE_IT: &str = "The recovery code: ";
if let RecoveryCommand::New { secrets: true, .. }
| RecoveryCommand::Confirm { secrets: true, .. }
| RecoveryCommand::Check { secrets: true } = command
{
unlock_secrets(library, false, environment, timings)?;
}
match command {
RecoveryCommand::New {
secrets,
revoke_older,
} => {
let new = (*secrets, *revoke_older);
recovery_new_command(library, new, json, environment, output)
}
RecoveryCommand::Confirm {
secrets,
revoke_older,
} => {
let code = typed_recovery_code(TYPE_IT, environment, json, output)?;
let standing = library
.check_recovery_code(&code)?
.code
.filter(|named| !named.revoked);
let already = standing.is_some();
let named = match standing {
Some(named) if !*secrets || named.holds_secrets => named,
_ => {
let now = environment.now();
library.add_recovery_code(&code, *secrets, now, environment.rng())?
}
};
let at_once = *revoke_older && named.replaced_by.is_none();
let now = environment.now();
let replaced =
library.revoke_replaced_recovery_codes(at_once, now, environment.rng())?;
let codes = library.recovery_codes()?;
output::recovery_confirmed(&named, already, (&replaced, &codes), json, output)
}
RecoveryCommand::List => {
let zone = environment.time_zone();
output::recovery_list(&library.recovery_codes()?, &zone, json, output)
}
RecoveryCommand::Check { .. } => {
let code = typed_recovery_code(TYPE_IT, environment, json, output)?;
let check = library.check_recovery_code(&code)?;
output::recovery_checked(&check, json, output)?;
if check.code.is_some() {
Ok(())
} else {
Err(CliError::UnknownRecoveryCode)
}
}
RecoveryCommand::Revoke { code, yes } => {
let mut named = library.find_recovery_code(code)?;
if *yes {
let now = environment.now();
named = library.revoke_recovery_code(code, now, environment.rng())?;
}
let zone = environment.time_zone();
output::recovery_revoked(&named, &zone, json, output)?;
if *yes {
Ok(())
} else {
Err(CliError::UnconfirmedRevoke)
}
}
RecoveryCommand::Restore { .. } | RecoveryCommand::FromCopy { .. } => {
unreachable!("run_command makes the library")
}
}
}
fn backup_command<E: Environment>(
library: &mut Library,
command: &BackupCommand,
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
let records = library.sync_records(UnwrapErr(SysRng))?;
let remembered: BTreeMap<EntityId, PathBuf> = records
.backup_folders()?
.into_iter()
.map(|(backup, found)| (backup, found.folder))
.collect();
match command {
BackupCommand::New {
folder,
name,
spaces,
policies,
away,
waits,
} => {
let spaces = spaces
.iter()
.map(|space| library.find_space(space))
.collect::<Result<Vec<_>, _>>()?;
let policies = backup_policies(library, &spaces, policies, environment)?;
let name = name.clone().unwrap_or_else(|| {
folder.file_name().map_or_else(
|| "Backup".to_owned(),
|name| name.to_string_lossy().into_owned(),
)
});
let new = NewBackup {
name,
spaces,
policies,
away: *away,
waits: waits.and_then(|Waits(days)| days),
};
backup_add(library, (folder, &new), &records, environment, json, output)
}
BackupCommand::List => backup_list(library, &remembered, environment, json, output),
BackupCommand::Update { backup, at } => {
let chosen = backups_to_update(library, backup.as_deref(), at.as_deref(), &remembered)?;
let mut failed = None;
for (backup, folder) in chosen {
let folder = std::path::absolute(&folder).unwrap_or(folder);
let now = || environment.now();
let updated = library.update_backup(&backup, &folder, &now, &|| false);
if let Ok(Some(_)) = &updated {
let kept = library.changes_kept()?;
records.record_backup(backup.id, &folder, Some((now(), kept)))?;
}
let shown = output::backup_updated(&backup, &folder, &updated, json, output);
if let Err(error) = updated {
failed.get_or_insert(error);
}
shown?;
}
failed.map_or(Ok(()), |error| Err(error.into()))
}
BackupCommand::Edit { .. } => backup_edit(library, command, environment, json, output),
BackupCommand::Remove { backup } => {
let known = library.find_backup(backup)?;
let now = environment.now();
library.remove_backup(known.id, now, environment.rng())?;
let folder = remembered.get(&known.id);
output::backup_removed(&known, folder.map(PathBuf::as_path), json, output)
}
}
}
fn backup_add<E: Environment>(
library: &mut Library,
(folder, new): (&Path, &NewBackup),
records: &nibkeep_node::Records,
environment: &mut E,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let now = environment.now();
let added = library.add_backup(folder, new, now, environment.rng())?;
let folder = std::path::absolute(folder).unwrap_or_else(|_| folder.to_owned());
let now = || environment.now();
let updated = library
.update_backup(&added.backup, &folder, &now, &|| false)?
.unwrap_or_default();
records.record_backup(
added.backup.id,
&folder,
Some((now(), library.changes_kept()?)),
)?;
output::backup_added(&added, &folder, &updated, json, output)
}
fn backup_list<E: Environment>(
library: &Library,
remembered: &BTreeMap<EntityId, PathBuf>,
environment: &E,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let found: BTreeMap<EntityId, PathBuf> = library
.find_backups(remembered)?
.into_iter()
.map(|(backup, folder)| (backup.id, folder))
.collect();
let now = environment.now();
let mut listed = Vec::new();
for backup in library.backups()? {
let state = found
.get(&backup.id)
.and_then(|folder| library.backup_state(&backup, folder, now).ok());
let spaces = backup
.spaces
.iter()
.map(|space| {
library
.space_name(*space)
.ok()
.flatten()
.unwrap_or_else(|| space.to_string())
})
.collect();
let policies = backup
.policies
.iter()
.map(|policy| {
backup
.spaces
.iter()
.find_map(|space| library.name(*space, *policy).ok().flatten())
.unwrap_or_else(|| policy.to_string())
})
.collect();
let folder = found.get(&backup.id).cloned();
listed.push(output::ListedBackup {
backup,
folder,
state,
spaces,
policies,
});
}
output::backups(&listed, json, output)
}
fn backups_to_update(
library: &Library,
backup: Option<&str>,
at: Option<&Path>,
remembered: &BTreeMap<EntityId, PathBuf>,
) -> Result<Vec<(Backup, PathBuf)>, NodeError> {
Ok(match (backup, at) {
(Some(reference), Some(folder)) => {
vec![(library.find_backup(reference)?, folder.to_owned())]
}
(None, Some(folder)) => {
let named = library
.backups()?
.into_iter()
.find(|known| nibkeep_node::backup_named_at(folder) == Some(known.id))
.ok_or_else(|| {
NodeError::WhichBackup(format!("{} is no backup of yours", folder.display()))
})?;
vec![(named, folder.to_owned())]
}
(Some(reference), None) => {
let backup = library.find_backup(reference)?;
let found = library
.find_backups(remembered)?
.into_iter()
.find(|(known, _)| known.id == backup.id)
.ok_or_else(|| {
NodeError::WhichBackup(format!(
"this computer does not find the backup {}; plug it in, or say where it is with --at",
backup.name
))
})?;
vec![found]
}
(None, None) => library.find_backups(remembered)?,
})
}
fn backup_policies<E: Environment>(
library: &mut Library,
spaces: &[SpaceId],
names: &[String],
environment: &mut E,
) -> Result<Vec<EntityId>, CliError> {
if names.is_empty() {
return Ok(Vec::new());
}
let spaces = if spaces.is_empty() {
library.spaces()
} else {
spaces.to_vec()
};
let downloads = environment.downloads();
for space in &spaces {
let now = environment.now();
library.install_policies(*space, downloads.as_deref(), now, environment.rng())?;
}
let mut found = Vec::new();
for name in names {
let policies: Vec<EntityId> = spaces
.iter()
.filter_map(|space| library.find_policy(*space, name).ok())
.collect();
if policies.is_empty() {
return Err(NodeError::NoEntity(format!(
"no policy of the backup's spaces is named {name}"
))
.into());
}
found.extend(policies);
}
found.sort();
found.dedup();
Ok(found)
}
fn policy_command<E: Environment>(
library: &mut Library,
command: &PolicyCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let downloads = environment.downloads();
let now = environment.now();
library.install_policies(space, downloads.as_deref(), now, environment.rng())?;
match command {
PolicyCommand::List => {
let policies = library.policies(space)?;
let rules = library.rules(space)?;
let name_of = |entity| library.name(space, entity).ok().flatten();
output::policies(&policies, &rules, &name_of, json, output)
}
PolicyCommand::Show { policy } => {
let id = library.find_policy(space, policy)?;
let policies = library.policies(space)?;
let rules = library.rules(space)?;
let name_of = |entity| library.name(space, entity).ok().flatten();
output::policy(id, &policies, &rules, &name_of, json, output)
}
PolicyCommand::New {
name,
copies,
away,
archived,
in_place,
} => {
let needs = Needs {
copies: *copies,
away: *away,
archived: *archived,
kept: if *in_place {
Kept::InPlace
} else {
Kept::Store
},
};
let id = library.add_policy(space, name, needs, now, environment.rng())?;
policy_changed("Added", id, library, json, output)
}
PolicyCommand::Edit {
policy,
name,
copies,
away,
archived,
in_place,
store,
} => {
let id = library.find_policy(space, policy)?;
let kept = match (*in_place, *store) {
(true, _) => Some(Kept::InPlace),
(_, true) => Some(Kept::Store),
_ => None,
};
let edit = PolicyEdit {
name: name.clone(),
copies: *copies,
away: *away,
archived: *archived,
kept,
};
library.edit_policy(space, id, &edit, now, environment.rng())?;
policy_changed("Changed", id, library, json, output)
}
PolicyCommand::Remove { policy } => {
let id = library.find_policy(space, policy)?;
let name = library
.policies(space)?
.into_iter()
.find(|known| known.id == id)
.and_then(|known| known.name);
library.remove_policy(space, id, now, environment.rng())?;
output::removed_policy(id, name.as_deref(), json, output)
}
PolicyCommand::Rule { command } => {
rule_command(library, command, json, environment, output)
}
PolicyCommand::Set {
entity,
policy,
clear: _,
} => {
let id = library.find_entity(space, entity)?;
let policy = policy
.as_deref()
.map(|policy| library.find_policy(space, policy))
.transpose()?;
library.set_policy(space, id, policy, now, environment.rng())?;
why(library, id, json, output)
}
PolicyCommand::Why { entity } => {
let id = library.find_entity(space, entity)?;
why(library, id, json, output)
}
PolicyCommand::Check => {
let check = library.check_policies(space, environment.now())?;
let name_of = |entity| library.name(space, entity).ok().flatten();
let zone = environment.time_zone();
output::policy_check(&check, (&name_of, &zone), json, output)
}
}
}
fn rule_command<E: Environment>(
library: &mut Library,
command: &RuleCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let now = environment.now();
match command {
RuleCommand::New {
policy,
of_type,
has,
folder,
media_type,
larger_than,
asks_above,
place,
} => {
let types = library.types(space)?;
let rule = NewRule {
of_type: of_type
.as_deref()
.map(|name| types::type_named(name, &types))
.transpose()?,
has: has
.as_deref()
.map(|field| types::field_named(field, &types, &[FILE, PHOTO, VIDEO]))
.transpose()?,
folder: folder.clone(),
media_type: media_type.clone(),
larger_than: *larger_than,
asks_above: *asks_above,
..NewRule::new(library.find_policy(space, policy)?)
};
let place = place_of(library, place)?.unwrap_or(Place::BeforeTheRest);
let id = library.add_rule(space, &rule, place, now, environment.rng())?;
rule_changed("Added", id, library, json, output)
}
RuleCommand::Remove { rule } => {
let id = rule_named(library, rule)?;
library.remove_rule(space, id, now, environment.rng())?;
output::removed_rule(id, json, output)
}
RuleCommand::Move { rule, place } => {
let id = rule_named(library, rule)?;
let place = place_of(library, place)?.ok_or(CliError::WhereTo)?;
library.move_rule(space, id, place, now, environment.rng())?;
rule_changed("Moved", id, library, json, output)
}
}
}
fn rule_changed(
what: &str,
id: EntityId,
library: &Library,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let rules = library.rules(space)?;
let policies = library.policies(space)?;
let name_of = |entity| library.name(space, entity).ok().flatten();
output::rule_changed(what, id, &rules, &policies, &name_of, json, output)
}
fn policy_changed(
what: &str,
id: EntityId,
library: &Library,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let policies = library.policies(library.default_space())?;
match policies.iter().find(|policy| policy.id == id) {
Some(policy) => output::policy_changed(what, policy, json, output),
None => Ok(()),
}
}
fn rule_named(library: &Library, text: &str) -> Result<EntityId, CliError> {
let rules = library.rules(library.default_space())?;
if let Some(rule) = text
.parse::<usize>()
.ok()
.and_then(|number| number.checked_sub(1))
.and_then(|index| rules.get(index))
{
return Ok(rule.id);
}
let lowered = text.to_lowercase();
let found: Vec<EntityId> = rules
.iter()
.map(|rule| rule.id)
.filter(|id| {
let id = id.to_string();
id == lowered || (lowered.len() >= 6 && id.starts_with(&lowered))
})
.collect();
match found.as_slice() {
[one] => Ok(*one),
_ => Err(CliError::NoRule(text.to_owned())),
}
}
fn place_of(library: &Library, place: &PlaceArgs) -> Result<Option<Place>, CliError> {
Ok(if place.first {
Some(Place::First)
} else if place.last {
Some(Place::Last)
} else if let Some(rule) = &place.before {
Some(Place::Before(rule_named(library, rule)?))
} else if let Some(rule) = &place.after {
Some(Place::After(rule_named(library, rule)?))
} else {
None
})
}
fn why(
library: &Library,
entity: EntityId,
json: bool,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let choice = library.policy_of(space, entity)?;
let policies = library.policies(space)?;
let rules = library.rules(space)?;
let name_of = |entity| library.name(space, entity).ok().flatten();
output::why(&choice, &policies, &rules, &name_of, json, output)
}
fn parse_size(text: &str) -> Result<u64, String> {
let text = text.trim();
let digits = text
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(text.len());
let (number, unit) = text.split_at(digits);
let number: u64 = number
.parse()
.map_err(|_| format!("{text} is not a size, such as 500MB or 2GiB"))?;
let unit = unit.trim().to_lowercase();
let size: u64 = match unit.as_str() {
"" | "b" => 1,
"kb" => 1_000,
"mb" => 1_000_000,
"gb" => 1_000_000_000,
"tb" => 1_000_000_000_000,
"kib" => 1 << 10,
"mib" => 1 << 20,
"gib" => 1 << 30,
"tib" => 1 << 40,
_ => {
return Err(format!(
"{unit} is not a unit of size: B, kB, MB, GB, TB, KiB, MiB, GiB or TiB"
));
}
};
number
.checked_mul(size)
.ok_or_else(|| format!("{text} is too large"))
}
fn gather(
path: &Path,
(given, own): (bool, &Path),
files: &mut Vec<PathBuf>,
found: &mut output::FilesAdded,
) {
let mut fail = |reason: String| found.failed.push((path.to_owned(), reason));
let metadata = if given {
std::fs::metadata(path)
} else {
std::fs::symlink_metadata(path)
};
let metadata = match metadata {
Ok(metadata) => metadata,
Err(error) => return fail(error.to_string()),
};
let is_own = || std::fs::canonicalize(path).is_ok_and(|resolved| resolved.starts_with(own));
if given && (metadata.is_file() || metadata.is_dir()) && is_own() {
return fail("the library's own folder holds it".to_owned());
}
if metadata.is_file() {
files.push(path.to_owned());
} else if metadata.is_dir() {
if !given && is_own() {
found.left_out += 1;
return;
}
let entries = match std::fs::read_dir(path) {
Ok(entries) => entries,
Err(error) => return fail(error.to_string()),
};
let mut inside = Vec::new();
for entry in entries {
match entry {
Ok(entry) => inside.push(entry.path()),
Err(error) => fail(error.to_string()),
}
}
inside.sort();
for entry in inside {
let hidden = entry
.file_name()
.is_some_and(|name| name.to_string_lossy().starts_with('.'));
if hidden {
found.left_out += 1;
} else {
gather(&entry, (false, own), files, found);
}
}
} else if given {
fail("neither a file nor a folder".to_owned());
} else {
found.left_out += 1;
}
}
fn secret_command<E: Environment>(
library: &mut Library,
command: &SecretCommand,
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (SecretCommand::Set { entity, field, .. }
| SecretCommand::Show { entity, field }
| SecretCommand::History { entity, field }
| SecretCommand::Clear { entity, field }
| SecretCommand::Purge { entity, field, .. }) = command
else {
return entityless_secret_command(library, command, json, environment, timings, output);
};
let (space, id) = library.locate_or_deleted(entity)?;
library.choose_space(Some(space))?;
let day = dating(environment, environment.now(), None).day;
let view = library
.entity(space, id, day)?
.ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
let types = library.types(space)?;
let field = types::field_named(field, &types, &view.types)?;
if !is_secret(library, space, &field) {
return Err(CliError::NotSecret(field));
}
let generated = generated_secret(command, &field, environment)?;
let set = matches!(command, SecretCommand::Set { .. });
unlock_secrets(library, set, environment, timings)?;
let no_value = || CliError::NoSecretValue {
entity: entity.clone(),
field: field.clone(),
};
let done = match command {
SecretCommand::Set { .. } => set_secret(
library,
(id, &field, &types),
generated,
environment,
timings,
),
SecretCommand::Clear { .. } => edit_now(
library,
id,
Edit::Set(field.clone(), Vec::new()),
environment,
),
SecretCommand::Purge { yes, .. } => (|| {
let asked = Instant::now();
let text = environment.passphrase(&format!("The value of {field} to purge: "))?;
add(&mut timings.waiting, asked.elapsed());
if text.is_empty() {
return Err(CliError::EmptyValue);
}
let value = types::value(&text, &field, &types, library, space)?;
let purged = purge_values(library, (id, &field, Some(&value)), *yes, environment)?;
let name_of = |entity| library.name(space, entity).ok().flatten();
let elsewhere = space_names(library, &purged.elsewhere);
output::purge(&purged, (&field, &name_of), &elsewhere, *yes, json, output)
})(),
SecretCommand::Show { .. } => (|| {
let view = library
.entity(space, id, day)?
.ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
let values = view.values(&field);
if values.is_empty() {
return Err(no_value());
}
let name_of = |entity| library.name(space, entity).ok().flatten();
output::secret_values(view.id, &field, values, &name_of, json, output)
})(),
SecretCommand::History { .. } => {
let history = (entity.as_str(), Some(field.as_str()));
history_command(library, history, json, environment, output).map_err(
|error| match error {
CliError::SecretHistory(_) => no_value(),
other => other,
},
)
}
SecretCommand::Copy { .. }
| SecretCommand::Generate { .. }
| SecretCommand::Code { .. }
| SecretCommand::Ask { .. }
| SecretCommand::Give { .. }
| SecretCommand::FromCopy
| SecretCommand::Save { .. } => {
unreachable!("answered above")
}
};
library.lock_secrets();
done?;
match command {
SecretCommand::Set { .. } | SecretCommand::Clear { .. } => {
let day = dating(environment, environment.now(), None).day;
show(library, space, id, When::on(day), json, output)
}
SecretCommand::Purge { yes: false, .. } => Err(CliError::Unconfirmed),
_ => Ok(()),
}
}
fn entityless_secret_command<E: Environment>(
library: &mut Library,
command: &SecretCommand,
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
match command {
SecretCommand::Code { entity, field } => {
let code = (entity.as_str(), field.as_deref());
code_command(library, code, json, environment, timings, output)
}
SecretCommand::Ask { from } => match shared_space(library) {
Some(space) => {
let asking = (space, from.as_str());
ask_space_command(library, asking, json, environment, timings, output)
}
None => ask_command(library, from, json, environment, timings, output),
},
SecretCommand::Give { device } => match shared_space(library) {
Some(space) => {
let giving = (space, device.as_str());
give_space_command(library, giving, json, environment, timings, output)
}
None => give_command(library, device, json, environment, timings, output),
},
SecretCommand::FromCopy => {
from_copy_secrets_command(library, json, environment, timings, output)
}
SecretCommand::Save { file, path } => {
let save = (file.as_str(), path.as_deref());
let saved = secret_save_command(library, save, json, environment, timings, output);
library.lock_secrets();
saved
}
_ => unreachable!("run_command runs nib secret generate and copy"),
}
}
fn secret_save_command<E: Environment>(
library: &mut Library,
(file, place): (&str, Option<&Path>),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (space, file) = library.locate(file)?;
library.choose_space(Some(space))?;
let place = match place {
Some(place) => absolute(place, environment)?,
None => current_dir(environment)?,
};
unlock_secrets(library, false, environment, timings)?;
let saved = library.save_secret_file(space, file, &place)?;
let name = library.name(space, file)?;
output::secret_saved((file, name.as_deref()), &saved, json, output)
}
fn shared_space(library: &Library) -> Option<SpaceId> {
library.chosen_space().filter(|&space| {
space != library.personal_space()
&& library
.members(space)
.is_ok_and(|members| members.iter().any(|member| !member.this_user))
})
}
fn member_device(
library: &Library,
space: SpaceId,
name: &str,
wanted: impl Fn(&nibkeep_node::MemberReplica) -> bool,
) -> Result<(String, nibkeep_node::MemberReplica), CliError> {
let mut found = Vec::new();
for member in library.members(space)? {
for replica in member.replicas {
let id = replica.record.to_string();
let named = replica.device.as_deref() == Some(name)
|| id == name
|| (name.len() >= 8 && id.starts_with(name));
if named && !replica.this && !replica.revoked && wanted(&replica) {
found.push((member.name.clone().unwrap_or_default(), replica));
}
}
}
match found.len() {
1 => Ok(found.remove(0)),
0 => Err(NodeError::WhichDevice(format!(
"no other member's device in the space that is {name} can do that; nib space \
members shows them"
))
.into()),
_ => Err(NodeError::WhichDevice(format!(
"{name} names several devices in the space; give the ID of the one you mean, as \
nib space show --json shows it"
))
.into()),
}
}
fn ask_space_command<E: Environment>(
library: &mut Library,
(space, from): (SpaceId, &str),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (member, device) = member_device(library, space, from, |replica| replica.holds_secrets)?;
if library.secrets_protection()?.is_none() {
return Err(NodeError::SetUpSecretsFirst.into());
}
unlock_secrets(library, false, environment, timings)?;
let now = environment.now();
let asked = library.ask_for_space_secrets(space, device.record, now, environment.rng());
library.lock_secrets();
asked?;
let name = library.space_name(space)?.unwrap_or_default();
output::asked_for_space_secrets(&name, (&member, &device), json, output)
}
fn give_space_command<E: Environment>(
library: &mut Library,
(space, to): (SpaceId, &str),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let (member, device) = member_device(library, space, to, |replica| replica.asks_for_secrets)?;
unlock_secrets(library, false, environment, timings)?;
let now = environment.now();
let given = library.give_space_secrets(space, device.record, now, environment.rng());
library.lock_secrets();
let keys = given?;
let name = library.space_name(space)?.unwrap_or_default();
output::gave_space_secrets(&name, (&member, &device), keys, json, output)
}
fn ask_command<E: Environment>(
library: &mut Library,
from: &str,
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let Some(from) = library
.replicas_named(from)?
.into_iter()
.find(|replica| replica.holds_secrets && !replica.this && !replica.revoked)
else {
return Err(NodeError::WhichDevice(
"that device does not hold the secrets, or has not said so yet: unlock its secrets \
once"
.to_owned(),
)
.into());
};
let now = environment.now();
if library.secrets_state()? == SecretsState::Asked {
library.ask_secrets_from(from.id, now, environment.rng())?;
} else {
library.check_may_ask(from.id)?;
let passphrase = ask_twice(
environment,
timings,
(
"A passphrase for the secrets on this device, not the library's: ",
"The passphrase again: ",
),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
)?;
let protection = NewProtection::Passphrase(&passphrase, environment.passphrase_params());
let now = environment.now();
let asked = library.ask_for_secrets(from.id, &protection, now, environment.rng());
library.lock_secrets();
asked?;
}
let own = library.replicas()?.into_iter().find(|replica| replica.this);
output::asked_for_secrets(own.as_ref(), &from, json, output)
}
fn give_command<E: Environment>(
library: &mut Library,
device: &str,
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let named: Vec<Replica> = library
.replicas_named(device)?
.into_iter()
.filter(|replica| !replica.this && !replica.revoked)
.collect();
if named.is_empty() {
return Err(NodeError::WhichDevice(
"that names no other device of yours that is not revoked".to_owned(),
)
.into());
}
let own = library.replicas()?.into_iter().find(|replica| replica.this);
let own = own.map(|replica| replica.id);
let asking: Vec<Replica> = named
.iter()
.filter(|replica| replica.asks_for_secrets && replica.secrets_from == own)
.cloned()
.collect();
if asking.is_empty() {
return Err(if named.iter().any(|replica| replica.asks_for_secrets) {
NodeError::WhichDevice("that device asks another of yours for the secrets".to_owned())
} else {
NodeError::NotAsked
}
.into());
}
unlock_secrets(library, false, environment, timings)?;
let mut given = Vec::new();
let mut failed = None;
for replica in asking {
let now = environment.now();
match library.give_secrets(replica.id, now, environment.rng()) {
Ok(keys) => given.push((replica, keys)),
Err(error) => {
failed = Some(error);
break;
}
}
}
library.lock_secrets();
output::gave_secrets(&given, json, output)?;
match failed {
Some(error) => Err(error.into()),
None => Ok(()),
}
}
fn generated_secret<E: Environment>(
command: &SecretCommand,
field: &FieldName,
environment: &mut E,
) -> Result<Option<zeroize::Zeroizing<String>>, CliError> {
let SecretCommand::Set {
generate, recipe, ..
} = command
else {
return Ok(None);
};
if !generate {
return if recipe.given() {
Err(CliError::RecipeWithoutGenerate)
} else {
Ok(None)
};
}
if *field == nibkeep_std::ONE_TIME_CODE {
return Err(CliError::GeneratedOneTimeCode(field.clone()));
}
Ok(Some(nibkeep_passwords::generate(
&recipe.recipe(),
environment.rng(),
)?))
}
fn set_secret<E: Environment>(
library: &mut Library,
(id, field, types): (EntityId, &FieldName, &nibkeep_model::Types),
generated: Option<zeroize::Zeroizing<String>>,
environment: &mut E,
timings: &mut Timings,
) -> Result<(), CliError> {
let text = if let Some(generated) = generated {
generated
} else {
ask_twice(
environment,
timings,
(&format!("{field}: "), &format!("{field} again: ")),
(|| CliError::EmptyValue, || CliError::ValuesDiffer),
)?
};
if *field == nibkeep_std::ONE_TIME_CODE {
nibkeep_passwords::OneTimeCode::check(&text)?;
}
let space = library.default_space();
let value = types::value(&text, field, types, library, space)?;
edit_now(
library,
id,
Edit::Set(field.clone(), vec![value]),
environment,
)
}
fn code_command<E: Environment>(
library: &mut Library,
(entity, field): (&str, Option<&str>),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let default = nibkeep_std::ONE_TIME_CODE;
let field = field.unwrap_or(default.as_str());
let read = read_secret(library, entity, field, environment, timings)?;
let generator = nibkeep_passwords::OneTimeCode::parse(&read.values[0])?;
output::one_time_code(&generator, environment.now() / 1000, json, output)
}
struct SecretRead {
entity: EntityId,
name: String,
field: FieldName,
values: Vec<zeroize::Zeroizing<String>>,
}
fn read_secret<E: Environment>(
library: &mut Library,
entity: &str,
field: &str,
environment: &mut E,
timings: &mut Timings,
) -> Result<SecretRead, CliError> {
let (space, id) = library.locate_or_deleted(entity)?;
library.choose_space(Some(space))?;
let day = dating(environment, environment.now(), None).day;
let view = library
.entity(space, id, day)?
.ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
let types = library.types(space)?;
let field = types::field_named(field, &types, &view.types)?;
if !is_secret(library, space, &field) {
return Err(CliError::NotSecret(field));
}
unlock_secrets(library, false, environment, timings)?;
let read = library.entity(space, id, day);
library.lock_secrets();
let view = read?.ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
let name_of = |entity| library.name(space, entity).ok().flatten();
let values: Vec<zeroize::Zeroizing<String>> = view
.values(&field)
.iter()
.map(|shown| zeroize::Zeroizing::new(output::value_text(&shown.value, &name_of)))
.collect();
if values.is_empty() {
return Err(CliError::NoSecretValue {
entity: entity.to_owned(),
field,
});
}
Ok(SecretRead {
entity: view.id,
name: view.name.unwrap_or_else(|| entity.to_owned()),
field,
values,
})
}
fn copy_and_clear<E: Environment>(
board: Box<dyn nibkeep_passwords::Board>,
read: &SecretRead,
clear_after: u64,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
environment.interruptible();
let mut clipboard = nibkeep_passwords::Clipboard::new(board, environment.rng());
clipboard.copy_secret(&read.values[0])?;
let printed = if json {
Ok(())
} else {
output::copied(
&read.field,
&read.name,
read.values.len(),
clear_after,
output,
)
.and_then(|()| Ok(output.flush()?))
};
let interrupted = printed.is_ok() && environment.wait(Duration::from_secs(clear_after));
let cleared = clipboard.clear_if_ours().or_else(|_| {
std::thread::sleep(Duration::from_millis(200));
clipboard.clear_if_ours()
});
printed?;
output::copy_ended(
(read.entity, &read.field, read.values.len()),
(cleared?, interrupted),
json,
output,
)
}
fn generate_command<E: Environment>(
recipe: &RecipeArgs,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let recipe = recipe.recipe();
let password = nibkeep_passwords::generate(&recipe, environment.rng())?;
output::generated(&password, recipe.bits(), json, output)
}
fn import_command<E: Environment>(
library: &mut Library,
(paths, from): (&[PathBuf], Option<&str>),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
if let [folder] = paths
&& ["manifest.json", "SHA256SUMS"]
.iter()
.any(|name| folder.join(name).is_file())
{
if from.is_some() {
return Err(CliError::Import(
"--from names the source of Google Takeout's photos; an export keeps where its files came from".to_owned(),
));
}
let space = library.default_space();
let imported = library.import(space, folder, environment.now(), environment.rng())?;
return output::imported(&imported, folder, json, output);
}
takeout_command(library, (paths, from), json, environment, output)
}
fn protect_command<E: Environment>(
library: &mut Library,
(passphrase, secrets): (bool, bool),
json: bool,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
if !passphrase && !environment.keystore() {
return Err(CliError::NoKeystoreToProtect);
}
if secrets {
unlock_secrets(library, false, environment, timings)?;
}
let protected = (|| {
let typed = if passphrase {
let prompt = if secrets {
"A new passphrase for the secrets, not the library's: "
} else {
"A new passphrase for the library: "
};
Some(ask_twice(
environment,
timings,
(prompt, "The passphrase again: "),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
)?)
} else {
None
};
let params = environment.passphrase_params();
let protection = match &typed {
Some(passphrase) => NewProtection::Passphrase(passphrase, params),
None => NewProtection::Keystore {
service: KEYSTORE_SERVICE,
},
};
let protected = if secrets {
library.protect_secrets(&protection, environment.rng())
} else {
library.protect(&protection, environment.rng())
};
protected.map_err(|error| match error {
error @ NodeError::Keys(KeysError::Keystore(_)) => CliError::KeystoreToProtect(error),
other => CliError::Node(other),
})
})();
library.lock_secrets();
protected?;
output::protected(secrets, passphrase, json, output)
}
fn edit_now<E: Environment>(
library: &mut Library,
entity: nibkeep_base::EntityId,
edit: Edit,
environment: &mut E,
) -> Result<(), CliError> {
let space = library.default_space();
let now = environment.now();
let dating = dating(environment, now, None);
library.edit_entity(space, entity, vec![edit], &dating, now, environment.rng())?;
Ok(())
}
fn is_secret(library: &Library, space: nibkeep_base::SpaceId, field: &FieldName) -> bool {
library
.secret_fields(space)
.is_some_and(|secret| secret.contains(field))
}
pub(crate) fn unlock_secrets<E: Environment>(
library: &mut Library,
set_up: bool,
environment: &mut E,
timings: &mut Timings,
) -> Result<(), CliError> {
match library.secrets_protection()? {
None if !set_up => return Err(CliError::NoSecrets),
None => {
let passphrase = ask_twice(
environment,
timings,
(
"The library's first secret. A passphrase for its secrets, not the library's: ",
"The passphrase again: ",
),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
)?;
let protection =
NewProtection::Passphrase(&passphrase, environment.passphrase_params());
let now = environment.now();
return Ok(library.set_up_secrets(&protection, now, environment.rng())?);
}
Some(Protection::Passphrase { .. }) => {
let asked = Instant::now();
let passphrase = environment.passphrase("Passphrase for secrets: ")?;
add(&mut timings.waiting, asked.elapsed());
library.unlock_secrets(&Unlocker::Passphrase(&passphrase))?;
}
Some(Protection::Keystore { .. }) => {
if !environment.keystore() {
return Err(CliError::NoKeystore);
}
library.unlock_secrets(&Unlocker::Keystore)?;
}
}
let now = environment.now();
let settled = library.settle_secrets(now, environment.rng());
let personal = library.personal_space();
if settled.is_err() || !library.secrets_unlocked(personal) {
library.lock_secrets();
}
settled?;
if library.secrets_unlocked(personal) {
Ok(())
} else {
Err(NodeError::SecretsAsked.into())
}
}
type Mistyped = (fn() -> CliError, fn() -> CliError);
fn ask_once<E: Environment>(
environment: &mut E,
timings: &mut Timings,
prompt: &str,
) -> Result<zeroize::Zeroizing<String>, CliError> {
let asked = Instant::now();
let typed = environment.passphrase(prompt);
add(&mut timings.waiting, asked.elapsed());
Ok(typed?)
}
fn ask_twice<E: Environment>(
environment: &mut E,
timings: &mut Timings,
(prompt, again): (&str, &str),
(empty, differ): Mistyped,
) -> Result<zeroize::Zeroizing<String>, CliError> {
let asked = Instant::now();
let first = environment.passphrase(prompt);
let second = match &first {
Ok(first) if !first.is_empty() => Some(environment.passphrase(again)),
_ => None,
};
add(&mut timings.waiting, asked.elapsed());
let first = first?;
let Some(second) = second else {
return Err(empty());
};
if *first != *second? {
return Err(differ());
}
Ok(first)
}
fn type_command<E: Environment>(
library: &mut Library,
command: &TypeCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.default_space();
let (name, types) = match command {
TypeCommand::Add { name, fields } => {
let name: TypeName = types::name(name)?;
let fields = fields
.iter()
.map(|field| types::field(field))
.collect::<Result<Vec<_>, _>>()?;
let known = library.types(space)?;
let type_known = types::standard_type_known(&known, &name);
types::check_standard(name.as_str(), "type", type_known)?;
for (field, definition) in &fields {
let field_known = types::standard_field_known(&known, field, definition);
types::check_standard(field.as_str(), "field", field_known)?;
if let Some(reverse) = definition.reverse() {
let reverse_known = types::standard_reverse_known(&known, reverse);
types::check_standard(reverse.as_str(), "field", reverse_known)?;
}
}
let definition = library.types(space)?.extend(name.clone(), fields);
let now = environment.now();
let types = library.define_type(space, &definition, now, environment.rng())?;
(name, types)
}
TypeCommand::Show { name } => (types::name(name)?, library.types(space)?),
TypeCommand::List => {
let types = library.types(space)?;
return output::type_list(&types, library.languages(), json, output);
}
};
let definition = types.get(&name).ok_or(CliError::NoType(name))?;
let secret = library.secret_fields(space).cloned().unwrap_or_default();
output::type_definition(definition, (library.languages(), &secret), json, output)
}
fn space_command<E: Environment>(
library: &mut Library,
command: &SpaceCommand,
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
match command {
SpaceCommand::New { .. }
| SpaceCommand::Take { .. }
| SpaceCommand::Drop { .. }
| SpaceCommand::Allow { .. } => taking_command(library, command, json, environment, output),
SpaceCommand::AddGroup { .. }
| SpaceCommand::RemoveGroup { .. }
| SpaceCommand::Agree { .. }
| SpaceCommand::Withdraw { .. } => group_command(library, command, json, environment, output),
SpaceCommand::List => {
let status = library.status()?;
let known = library.known_spaces()?;
let requests = library.space_requests()?;
output::spaces(
(&status.spaces, &known, &requests),
library.personal_space(),
json,
output,
)
}
SpaceCommand::Show { space } => {
show_space_command(library, space, json, environment, output)
}
SpaceCommand::Rename { space, name } => {
let space = library.find_space(space)?;
let now = environment.now();
library.rename_space(space, name, now, environment.rng())?;
output::space_renamed(space, name, json, output)
}
SpaceCommand::Invite {
space,
role,
person,
yes,
..
} => {
let space = library.find_space(space)?;
let person = person
.as_deref()
.map(|person| library.find_person(space, person))
.transpose()?;
let invitation = nibkeep_node::Invitation {
space,
role: role.role(),
person,
};
invite_command(library, (&invitation, *yes), cli, environment, output)
}
SpaceCommand::Join { code, yes, on } => {
let also = devices_named(library, on)?;
join_space_command(library, (code, *yes, &also), cli, environment, output)
}
SpaceCommand::AiAgents { space, switch } => {
let space = library.find_space(space)?;
if let Some(switch) = switch {
let now = environment.now();
library.allow_ai_agents(space, *switch == Switch::On, now, environment.rng())?;
}
let allowed = library.ai_agents_allowed(space)?;
output::ai_agents_allowed(allowed, json, output)
}
SpaceCommand::Link {
space,
member,
person,
} => link_command(
library,
(space, member, person.as_deref()),
json,
environment,
output,
),
SpaceCommand::Accept { space, member, yes } => {
accept_in_space_command(library, (space, member, *yes), json, environment, output)
}
SpaceCommand::Leave { space, yes } => {
let space = library.find_space(space)?;
leave_command(library, (space, *yes), json, environment, output)
}
SpaceCommand::Remove { space, member, yes } => {
remove_command(library, (space, member, *yes), json, environment, output)
}
SpaceCommand::LetIn { .. }
| SpaceCommand::MakeDirect { .. }
| SpaceCommand::Confirm { .. } => direct_command(library, command, json, environment, output),
SpaceCommand::Claim { .. } | SpaceCommand::Reject { .. } => {
claim_command(library, command, json, environment, output)
}
SpaceCommand::Role {
space,
member,
role,
} => role_command(library, (space, member, *role), json, environment, output),
}
}
fn taking_command<E: Environment>(
library: &mut Library,
command: &SpaceCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
match command {
SpaceCommand::New { name, group, on } => {
let also = devices_named(library, on)?;
let now = environment.now();
let space = if *group {
library.create_group_on(name, &also, now, environment.rng())?
} else {
library.create_space_on(name, &also, now, environment.rng())?
};
output::space_made(space, name, json, output)
}
SpaceCommand::Take { wanted } => {
let space = library.find_known_space(wanted)?;
let now = environment.now();
let taking = library.take_space(space, now, environment.rng())?;
let name = library
.known_spaces()?
.into_iter()
.find(|known| known.space == space)
.and_then(|known| known.name)
.unwrap_or_else(|| space.to_string());
let this = library
.replicas()?
.into_iter()
.find(|replica| replica.this)
.ok_or(NodeError::NotListed)?;
let named = (this.device_name.as_deref(), this.id);
output::space_taken((space, &name), taking, named, json, output)
}
SpaceCommand::Drop { wanted } => {
let space = library.find_space(wanted)?;
let name = library
.space_name(space)?
.unwrap_or_else(|| space.to_string());
let now = environment.now();
let dropping = library.drop_space(space, now, environment.rng())?;
output::space_dropping(&dropping, &name, json, output)
}
SpaceCommand::Allow { space, device } => {
let space = library.find_space(space)?;
let replicas = devices_named(library, std::slice::from_ref(device))?;
let request = library
.space_requests()?
.into_iter()
.find(|request| request.space == space && replicas.contains(&request.replica))
.ok_or(NodeError::NoRequest)?;
let now = environment.now();
library.allow_space(space, request.replica, now, environment.rng())?;
output::space_allowed(&request, json, output)
}
_ => unreachable!("only nib space new, take, drop and allow come here"),
}
}
fn role_command<E: Environment>(
library: &mut Library,
(space, member, role): (&str, &str, RoleArg),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.find_space(space)?;
let member = library.find_member(space, member)?;
let now = environment.now();
library.give_role(space, member, role.role(), now, environment.rng())?;
let name = library
.members(space)?
.into_iter()
.find(|found| found.record == member)
.and_then(|found| found.name);
output::role_given(name.as_deref(), role.role(), json, output)
}
fn accept_in_space_command<E: Environment>(
library: &mut Library,
(space, member, confirmed): (&str, &str, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.find_space(space)?;
let chosen = library.find_member(space, member)?;
let members = library.members(space)?;
let user = members
.iter()
.find(|found| found.record == chosen)
.and_then(|found| found.user);
let records: Vec<_> = members
.iter()
.filter(|found| found.record == chosen || (user.is_some() && found.user == user))
.map(|found| found.record)
.collect();
let changes: Vec<_> = library
.set_aside_in(space)?
.into_iter()
.filter(|aside| {
aside.acceptable && aside.member.is_some_and(|member| records.contains(&member))
})
.map(|aside| aside.change)
.collect();
let accepted = if confirmed {
let now = environment.now();
library.accept_set_aside_in(space, &changes, now, environment.rng())?
} else {
library.check_admin(space, "accept changes that were set aside")?;
changes.len()
};
output::accepted(accepted, confirmed, json, output)?;
if confirmed || accepted == 0 {
Ok(())
} else {
Err(CliError::UnconfirmedAccept)
}
}
fn leave_command<E: Environment>(
library: &mut Library,
(space, confirmed): (nibkeep_base::SpaceId, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let name = library
.space_name(space)?
.unwrap_or_else(|| space.to_string());
if !confirmed {
let closes = library.check_leave(space)?;
output::leaving(&name, closes, json, output)?;
return Err(CliError::UnconfirmedLeave);
}
let now = environment.now();
let closed = library.leave(space, now, environment.rng())?;
output::left(&name, closed, json, output)
}
fn space_display_name(library: &Library, space: nibkeep_base::SpaceId) -> Result<String, CliError> {
Ok(library
.space_name(space)?
.unwrap_or_else(|| space.to_string()))
}
fn keep_out_command<E: Environment>(
library: &mut Library,
(space, member, confirmed): (nibkeep_base::SpaceId, &str, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let found = library.find_group_member(space, member)?;
let name = space_display_name(library, space)?;
if !confirmed {
library.check_admin(space, "keep members out")?;
output::removing((&name, Some(member)), json, output)?;
return Err(CliError::UnconfirmedRemove);
}
let now = environment.now();
library.keep_out(space, found, now, environment.rng())?;
output::removed((&name, Some(member)), json, output)
}
fn remove_command<E: Environment>(
library: &mut Library,
(space, member, confirmed): (&str, &str, bool),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.find_space(space)?;
let record = match library.find_member(space, member) {
Ok(record) => record,
Err(NodeError::NoMember(_)) => {
return keep_out_command(
library,
(space, member, confirmed),
json,
environment,
output,
);
}
Err(error) => return Err(error.into()),
};
if library.check_remove(space, record)? {
return leave_command(library, (space, confirmed), json, environment, output);
}
let space_name = space_display_name(library, space)?;
let name = library
.members(space)?
.into_iter()
.find(|found| found.record == record)
.and_then(|found| found.name);
if !confirmed {
output::removing((&space_name, name.as_deref()), json, output)?;
return Err(CliError::UnconfirmedRemove);
}
let now = environment.now();
library.remove_member(space, record, now, environment.rng())?;
output::removed((&space_name, name.as_deref()), json, output)
}
fn show_space_command<E: Environment>(
library: &Library,
space: &str,
json: bool,
environment: &E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.find_space(space)?;
let members = library.members(space)?;
let mut names = std::collections::BTreeMap::new();
for member in &members {
let link = member.person;
for person in [link.holds, link.by_admin, link.by_member]
.into_iter()
.flatten()
{
if let Some(name) = library.name(space, person)? {
names.insert(person, name);
}
}
}
let requests = if library.is_group(space)? {
Some(library.join_requests(space)?)
} else {
None
};
let shown = output::SpaceShown {
members: &members,
names: &names,
groups: &library.space_groups(space)?,
requests: requests.as_deref(),
claims: &library.claims(space)?,
set_aside: &library.set_aside_in(space)?,
};
output::space_shown(&shown, &environment.time_zone(), json, output)
}
fn purge_or_list<E: Environment>(
library: &mut Library,
cli: &Cli,
environment: &mut E,
timings: &mut Timings,
output: &mut dyn Write,
) -> Result<(), CliError> {
let Command::Purge {
entity, value, yes, ..
} = &cli.command
else {
unreachable!("nib purge is the command");
};
let Some(entity) = entity else {
return behind_command(library, cli, output);
};
let purge = (entity.as_str(), value.as_deref(), *yes);
purge_either(library, purge, cli.json, environment, timings, output)
}
fn behind_command(library: &Library, cli: &Cli, output: &mut dyn Write) -> Result<(), CliError> {
let spaces = if cli.space.is_some() {
vec![library.default_space()]
} else {
library.spaces()
};
let mut shown = Vec::new();
for left_in in spaces {
for request in library.purge_requests(left_in)? {
let (now_in, moved) = request.moved_into;
shown.push(output::LeftBehind {
request,
left_in: (left_in, library.space_name(left_in)?),
name: library.name(now_in, moved)?,
now_in: library.space_name(now_in)?,
});
}
}
output::purge_requests(&shown, cli.json, output)
}
fn claim_command<E: Environment>(
library: &mut Library,
command: &SpaceCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
match command {
SpaceCommand::Claim { space, yes } => {
let space = library.find_space(space)?;
let name = space_display_name(library, space)?;
if !*yes {
library.check_claim(space)?;
output::claiming(&name, json, output)?;
return Err(CliError::UnconfirmedClaim);
}
let now = environment.now();
library.claim_admin(space, now, environment.rng())?;
output::claimed(&name, json, output)
}
SpaceCommand::Reject { space, member } => {
let space = library.find_space(space)?;
let record = library.find_member(space, member)?;
let now = environment.now();
library.reject_claim(space, record, now, environment.rng())?;
let name = space_display_name(library, space)?;
output::rejected_claim((&name, member), json, output)
}
_ => unreachable!("space_command passes only these"),
}
}
fn direct_command<E: Environment>(
library: &mut Library,
command: &SpaceCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
match command {
SpaceCommand::LetIn { space, member } => {
let space = library.find_space(space)?;
let found = library.find_group_member(space, member)?;
let now = environment.now();
library.let_in(space, found, now, environment.rng())?;
let name = space_display_name(library, space)?;
output::let_in((&name, member), json, output)
}
SpaceCommand::MakeDirect {
space,
member,
role,
} => {
let space = library.find_space(space)?;
let found = library.find_group_member(space, member)?;
let now = environment.now();
library.make_direct(space, found, role.role(), now, environment.rng())?;
let name = space_display_name(library, space)?;
output::made_direct((&name, member), role.role(), json, output)
}
SpaceCommand::Confirm { space } => {
let space = library.find_space(space)?;
let now = environment.now();
library.confirm_direct(space, now, environment.rng())?;
let name = space_display_name(library, space)?;
output::confirmed_direct(&name, json, output)
}
_ => unreachable!("space_command passes only these"),
}
}
fn group_command<E: Environment>(
library: &mut Library,
command: &SpaceCommand,
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
match command {
SpaceCommand::AddGroup { space, group, role } => {
let (space, group) = (library.find_space(space)?, library.find_space(group)?);
let now = environment.now();
library.add_group(space, group, role.role(), now, environment.rng())?;
let groups = library.space_groups(space)?;
output::space_groups(&groups, json, output)
}
SpaceCommand::RemoveGroup { space, group } => {
let (space, group) = (library.find_space(space)?, library.find_space(group)?);
let now = environment.now();
library.remove_group(space, group, now, environment.rng())?;
output::space_groups(&library.space_groups(space)?, json, output)
}
SpaceCommand::Agree { group, space } | SpaceCommand::Withdraw { group, space } => {
let group = library.find_space(group)?;
let space = requested_space(library, group, space)?;
let now = environment.now();
if matches!(command, SpaceCommand::Withdraw { .. }) {
library.withdraw_group(group, space, now, environment.rng())?;
} else {
library.agree_to_join(group, space, now, environment.rng())?;
}
output::join_requests(&library.join_requests(group)?, json, output)
}
_ => Ok(()),
}
}
fn requested_space(
library: &Library,
group: nibkeep_base::SpaceId,
reference: &str,
) -> Result<nibkeep_base::SpaceId, CliError> {
let lowered = reference.to_lowercase();
let requests = library.join_requests(group)?;
let by_name: Vec<nibkeep_base::SpaceId> = requests
.iter()
.filter(|request| {
request
.name
.as_deref()
.is_some_and(|name| name.to_lowercase() == lowered)
})
.map(|request| request.space)
.collect();
let found: Vec<nibkeep_base::SpaceId> = if by_name.is_empty() && lowered.len() >= 4 {
requests
.iter()
.filter(|request| request.space.to_string().starts_with(&lowered))
.map(|request| request.space)
.collect()
} else {
by_name
};
match found.as_slice() {
[space] => Ok(*space),
[] => Err(nibkeep_node::NodeError::NoGroupRequest.into()),
_ => Err(nibkeep_node::NodeError::SpacesNamed(reference.to_owned()).into()),
}
}
fn link_command<E: Environment>(
library: &mut Library,
(space, member, person): (&str, &str, Option<&str>),
json: bool,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let space = library.find_space(space)?;
let member = library.find_member(space, member)?;
let person = person
.map(|person| library.find_person(space, person))
.transpose()?;
let now = environment.now();
library.link_member(space, member, person, now, environment.rng())?;
let found = library
.members(space)?
.into_iter()
.find(|found| found.record == member);
let name = found.as_ref().and_then(|found| found.name.clone());
let link = found.map_or_default(|found| found.person);
let person = match person {
Some(person) => Some((person, library.name(space, person)?)),
None => None,
};
output::linked(name.as_deref(), (person, link), json, output)
}
const INVITATION_MINUTES: u64 = 10;
fn invite_command<E: Environment>(
library: &mut Library,
(invitation, confirmed): (&nibkeep_node::Invitation, bool),
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
let (space, role) = (invitation.space, invitation.role);
library.check_admin(space, "invite")?;
if !confirmed && !environment.can_ask() {
return Err(CliError::UnconfirmedInvite);
}
let name = library
.space_name(space)?
.unwrap_or_else(|| space.to_string());
let suggest = role != MemberRole::Admin && library.suggests_second_admin(space)?;
let _borrowed =
nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
let code = PairingCode::generate(environment.rng());
let network = library.network(cli.network(true))?;
output::port_taken(&network, json, output)?;
output::invitation_code(
&code,
(&name, role),
(INVITATION_MINUTES, suggest),
json,
output,
)?;
let now = clock(environment);
let mut unasked = false;
let mut confirm = |invitee: &nibkeep_node::Invitee| {
if confirmed {
return true;
}
let question = output::invitee_question(invitee, (&name, role));
if let Ok(Some(answer)) = environment.ask(&question) {
matches!(answer.to_lowercase().as_str(), "y" | "yes")
} else {
unasked = true;
false
}
};
let printing = RefCell::new(output);
let wrong_try = |error: &NodeError, left: usize| {
let _ = output::wrong_try(error, left, json, &mut **printing.borrow_mut());
};
let invited = nibkeep_node::invite(
library,
&network,
invitation,
&code,
&mut confirm,
nibkeep_node::Showing {
timeout: Duration::from_mins(INVITATION_MINUTES),
wrong_try: &wrong_try,
},
&now,
&mut UnwrapErr(SysRng),
);
match invited {
Err(NodeError::Declined) if unasked => Err(CliError::UnconfirmedInvite),
invited => output::invited(&invited?, (&name, role), json, printing.into_inner()),
}
}
fn join_space_command<E: Environment>(
library: &mut Library,
(code, confirmed, also): (&PairingCode, bool, &[EntityId]),
cli: &Cli,
environment: &mut E,
output: &mut dyn Write,
) -> Result<(), CliError> {
let json = cli.json;
library.check_not_ai_agent("join spaces")?;
let _borrowed =
nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
let network = library.network(cli.network(false))?;
output::progress("Looking for the device that shows the code…", json, output)?;
let now = clock(environment);
let joined = nibkeep_node::join_space(
library,
&network,
code,
FIND_SPONSOR,
&now,
environment.rng(),
)?;
if !also.is_empty() {
let now = environment.now();
library.give_space(joined.space, also, now, environment.rng())?;
}
let linked = match &joined.person {
None => None,
Some((person, name)) => {
let yes = confirmed
|| matches!(
environment.ask(&output::person_question(name, &joined.name)),
Ok(Some(answer)) if matches!(answer.to_lowercase().as_str(), "y" | "yes")
);
let now = environment.now();
let linked = yes
&& match library.link_member(
joined.space,
joined.member,
Some(*person),
now,
environment.rng(),
) {
Ok(()) => true,
Err(error) => {
environment.note(&format!("could not link you to {name}: {error}"));
false
}
};
Some(linked)
}
};
output::joined_space(&joined, linked, json, output)
}
fn no_journal(error: CliError, directory: &Path) -> CliError {
match error {
CliError::Node(NodeError::NoJournal) => CliError::NoJournal(directory.to_owned()),
other => other,
}
}
fn init<E: Environment>(
directory: &Path,
new: &NewLibrary<'_>,
(passphrase, file): (bool, Option<&Path>),
environment: &mut E,
timings: &mut Timings,
) -> Result<Library, CliError> {
if Library::exists(directory) {
return Err(match Library::protection(directory) {
Err(NodeError::Unfinished) => unfinished(directory),
Err(NodeError::Copied) => CliError::CopiedHere(directory.to_owned()),
_ => NodeError::Exists.into(),
});
}
if let Some(first) = new_passphrase((passphrase, file), environment, timings)? {
let protection = NewProtection::Passphrase(&first, environment.passphrase_params());
create(directory, new, &protection, environment)
} else {
let protection = NewProtection::Keystore {
service: KEYSTORE_SERVICE,
};
create(directory, new, &protection, environment).map_err(|error| match error {
CliError::Node(error @ NodeError::Keys(KeysError::Keystore(_))) => {
CliError::Keystore(error)
}
other => other,
})
}
}
fn new_passphrase<E: Environment>(
(passphrase, file): (bool, Option<&Path>),
environment: &mut E,
timings: &mut Timings,
) -> Result<Option<zeroize::Zeroizing<String>>, CliError> {
if !(passphrase || file.is_some() || !environment.keystore()) {
return Ok(None);
}
Ok(Some(match file {
Some(file) => passphrase_in(file)?,
None => ask_twice(
environment,
timings,
("A passphrase for the library: ", "The passphrase again: "),
(|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
)?,
}))
}
fn passphrase_in(path: &Path) -> Result<zeroize::Zeroizing<String>, CliError> {
use std::io::Read;
let unreadable = |error: io::Error| CliError::PassphraseFile {
path: path.to_owned(),
error,
};
let mut file = std::fs::File::open(path).map_err(unreadable)?;
let metadata = file.metadata().map_err(unreadable)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
return Err(CliError::PassphraseFileOpen(path.to_owned()));
}
}
let room = usize::try_from(metadata.len()).unwrap_or(0);
let mut text = zeroize::Zeroizing::new(String::with_capacity(room + 1));
file.read_to_string(&mut text).map_err(unreadable)?;
let end = text.find(['\n', '\r']).unwrap_or(text.len());
text.truncate(end);
if text.is_empty() {
return Err(CliError::EmptyPassphrase);
}
Ok(text)
}
fn create<E: Environment>(
directory: &Path,
new: &NewLibrary<'_>,
protection: &NewProtection<'_>,
environment: &mut E,
) -> Result<Library, CliError> {
let now = environment.now();
let mut library = Library::create(directory, new, protection, now, environment.rng())?;
library.make_thumbnails_with(Arc::new(RustDecoders));
Ok(library)
}
fn open<E: Environment>(
directory: &Path,
passphrase_file: Option<&Path>,
environment: &mut E,
timings: &mut Timings,
) -> Result<Library, CliError> {
let started = Instant::now();
let mut waited = Duration::ZERO;
let (mut library, opening) = match Library::protection(directory)? {
Protection::Passphrase { .. } => {
let passphrase = if let Some(file) = passphrase_file {
passphrase_in(file)?
} else {
let asked = Instant::now();
let passphrase = environment.passphrase("Passphrase: ")?;
waited = asked.elapsed();
add(&mut timings.waiting, waited);
passphrase
};
Library::open_timed(directory, &Unlocker::Passphrase(&passphrase))?
}
Protection::Keystore { .. } => {
if !environment.keystore() {
return Err(CliError::NoKeystore);
}
Library::open_timed(directory, &Unlocker::Keystore)?
}
};
add(
&mut timings.unlock,
started.elapsed().saturating_sub(waited + opening.spaces),
);
add(&mut timings.open, opening.spaces);
library.make_thumbnails_with(Arc::new(RustDecoders));
Ok(library)
}
#[cfg(test)]
mod tests {
use std::io::{self, Write};
use super::{CliError, UntilUnread, parse_size};
struct Closing {
written: Vec<u8>,
room: usize,
error: io::ErrorKind,
}
impl Write for Closing {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if self.written.len() + bytes.len() > self.room {
return Err(self.error.into());
}
self.written.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn output_that_nothing_reads_is_taken_and_not_written() {
let closing = Closing {
written: Vec::new(),
room: 6,
error: io::ErrorKind::BrokenPipe,
};
let mut output = UntilUnread::new(closing);
writeln!(output, "first").expect("written");
writeln!(output, "second").expect("taken");
writeln!(output, "third").expect("taken");
output.flush().expect("flushed");
assert_eq!(output.inner.written, b"first\n");
assert!(output.unread);
let mut full = UntilUnread::new(Closing {
written: Vec::new(),
room: 0,
error: io::ErrorKind::StorageFull,
});
assert_eq!(
writeln!(full, "first").expect_err("full").kind(),
io::ErrorKind::StorageFull
);
assert!(!full.unread);
}
#[test]
fn sizes_are_read_in_bytes_and_units() {
assert_eq!(parse_size("1073741824"), Ok(1 << 30));
assert_eq!(parse_size("1GiB"), Ok(1 << 30));
assert_eq!(parse_size("500 MB"), Ok(500_000_000));
assert_eq!(parse_size("10b"), Ok(10));
assert!(parse_size("1.5GB").is_err());
assert!(parse_size("GB").is_err());
assert!(parse_size("2PB").is_err());
assert!(parse_size("99999999TiB").is_err());
assert_eq!(super::output::size_text(1 << 30), "1 GiB");
assert_eq!(super::output::size_text(500_000_000), "500 MB");
assert_eq!(super::output::size_text(22), "22 bytes");
}
#[test]
fn an_unsound_library_counts_its_problems() {
assert_eq!(
CliError::Unsound(1).to_string(),
"the library has a problem"
);
assert_eq!(
CliError::Unsound(3).to_string(),
"the library has 3 problems"
);
}
}