@xiaolikt/ai-vault 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Cargo.lock +1 -1
- package/README.md +395 -243
- package/README.zh.md +417 -0
- package/crates/ai-vault/Cargo.toml +1 -1
- package/crates/ai-vault/src/cli.rs +300 -88
- package/crates/ai-vault/src/dialog.rs +14 -7
- package/crates/ai-vault/src/i18n.rs +56 -0
- package/crates/ai-vault/src/import.rs +85 -48
- package/crates/ai-vault/src/main.rs +1 -0
- package/crates/ai-vault/src/store.rs +237 -5
- package/package.json +5 -5
- package/packages/pi-ai-vault/README.md +40 -45
- package/packages/pi-ai-vault/README.zh.md +84 -0
- package/packages/pi-ai-vault/package.json +5 -4
- package/packages/pi-ai-vault/src/bitwarden.ts +41 -25
- package/packages/pi-ai-vault/src/cli.ts +11 -4
- package/packages/pi-ai-vault/src/ente.ts +4 -3
- package/packages/pi-ai-vault/src/i18n.ts +31 -0
- package/packages/pi-ai-vault/src/import-map.ts +166 -58
- package/packages/pi-ai-vault/src/index.ts +194 -114
- package/packages/pi-ai-vault/src/prompt.ts +3 -2
- package/packages/pi-ai-vault/src/types.ts +52 -0
- package/test/cli.sh +44 -0
- package/tests/bitwarden-tools.test.mjs +2 -2
- package/tests/import-map.test.mjs +75 -38
- package/tests/mocks/bin/bw +5 -1
- package/tests/mocks/bin/zenity +7 -2
- package/tests/vault-cli.test.mjs +56 -0
|
@@ -12,10 +12,11 @@ use crate::sealed::{self, Kind};
|
|
|
12
12
|
use crate::config::{self, ImportPolicy, UnlockMode, UnlockPolicy};
|
|
13
13
|
use crate::crypto::{self, Kdf};
|
|
14
14
|
use crate::dialog::{self, Answer};
|
|
15
|
+
use crate::i18n::{tr, tr_owned};
|
|
15
16
|
use crate::import;
|
|
16
17
|
use crate::paths::{Paths, GRANT_MS_DEFAULT, GRANT_MS_MAX, IDLE_MS_DEFAULT};
|
|
17
18
|
use crate::session::{self, Session, StoreLock};
|
|
18
|
-
use crate::store::{
|
|
19
|
+
use crate::store::{Draft, Item, ItemType, self};
|
|
19
20
|
use crate::{audit, store::ItemSummary};
|
|
20
21
|
|
|
21
22
|
#[derive(Parser, Debug)]
|
|
@@ -136,17 +137,29 @@ enum Cmd {
|
|
|
136
137
|
#[arg(long, value_name = "HEX")]
|
|
137
138
|
approval: Option<String>,
|
|
138
139
|
},
|
|
139
|
-
/// Create or update an entry; the
|
|
140
|
+
/// Create or update an entry of any type; the secret is typed in a dialog
|
|
140
141
|
Add {
|
|
141
142
|
#[arg(long)]
|
|
142
143
|
name: String,
|
|
144
|
+
/// login (default) | note | card | identity | sshkey | bankaccount | driverslicense | passport
|
|
145
|
+
#[arg(long, value_name = "TYPE")]
|
|
146
|
+
r#type: Option<String>,
|
|
143
147
|
#[arg(long)]
|
|
144
148
|
username: Option<String>,
|
|
145
149
|
#[arg(long)]
|
|
146
150
|
uri: Option<String>,
|
|
147
151
|
#[arg(long)]
|
|
148
152
|
notes: Option<String>,
|
|
149
|
-
///
|
|
153
|
+
/// A field of the type, NAME=VALUE; repeatable. A field given as NAME
|
|
154
|
+
/// alone, or any hidden field left out, is typed in a dialog (or sent
|
|
155
|
+
/// on stdin for the primary one with --password-stdin).
|
|
156
|
+
#[arg(long = "field", value_name = "NAME[=VALUE]")]
|
|
157
|
+
fields: Vec<String>,
|
|
158
|
+
/// A hidden field supplied by a host that already asked the user for
|
|
159
|
+
/// it, NAME=VALUE; repeatable. Never printed, never in a window.
|
|
160
|
+
#[arg(long = "secret", value_name = "NAME=VALUE")]
|
|
161
|
+
secrets: Vec<String>,
|
|
162
|
+
/// Read the secret from stdin instead of a dialog
|
|
150
163
|
#[arg(long)]
|
|
151
164
|
password_stdin: bool,
|
|
152
165
|
/// Skip the "save this?" confirm window (the user already approved)
|
|
@@ -217,6 +230,8 @@ enum Fault {
|
|
|
217
230
|
Usage(String),
|
|
218
231
|
/// No desktop window could be opened; the host must supply the value.
|
|
219
232
|
NeedsUi(&'static str),
|
|
233
|
+
/// The same, for one named hidden field of a typed entry.
|
|
234
|
+
NeedsUiField(String),
|
|
220
235
|
Denied(String),
|
|
221
236
|
Auth(String),
|
|
222
237
|
}
|
|
@@ -226,7 +241,7 @@ impl Fault {
|
|
|
226
241
|
match self {
|
|
227
242
|
Fault::Error(_) => 1,
|
|
228
243
|
Fault::Usage(_) => 2,
|
|
229
|
-
Fault::NeedsUi(_) => 3,
|
|
244
|
+
Fault::NeedsUi(_) | Fault::NeedsUiField(_) => 3,
|
|
230
245
|
Fault::Denied(_) => 4,
|
|
231
246
|
Fault::Auth(_) => 5,
|
|
232
247
|
}
|
|
@@ -265,6 +280,11 @@ pub fn run() -> i32 {
|
|
|
265
280
|
eprintln!("needs-ui: {step}");
|
|
266
281
|
eprintln!("no desktop window is available; the host must supply this value");
|
|
267
282
|
}
|
|
283
|
+
Fault::NeedsUiField(field) => {
|
|
284
|
+
eprintln!("needs-ui: password field={field}");
|
|
285
|
+
eprintln!("no desktop window is available; the host must supply this value");
|
|
286
|
+
}
|
|
287
|
+
// (NeedsUi with a detail is printed by `needs_ui` below)
|
|
268
288
|
Fault::Usage(message) => eprintln!("ai-vault: {message}"),
|
|
269
289
|
Fault::Error(message) | Fault::Denied(message) | Fault::Auth(message) => {
|
|
270
290
|
eprintln!("ai-vault: {message}")
|
|
@@ -336,8 +356,8 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
|
|
|
336
356
|
Cmd::Get { name, token, reason, answer_stdin, approval } => {
|
|
337
357
|
get(paths, &out, token, &name, reason.as_deref(), answer_stdin, approval)
|
|
338
358
|
}
|
|
339
|
-
Cmd::Add { name, username, uri, notes, password_stdin, yes, token } => {
|
|
340
|
-
add(paths, &out, token, AddRequest { name, username, uri, notes, password_stdin, yes })
|
|
359
|
+
Cmd::Add { name, r#type, username, uri, notes, fields, secrets, password_stdin, yes, token } => {
|
|
360
|
+
add(paths, &out, token, AddRequest { name, r#type, username, uri, notes, fields, secrets, password_stdin, yes })
|
|
341
361
|
}
|
|
342
362
|
Cmd::Save { token, file, yes } => save(paths, &out, token, file, yes),
|
|
343
363
|
Cmd::Remove { name, yes, token } => remove(paths, &out, token, &name, yes),
|
|
@@ -454,11 +474,17 @@ fn ask_password(title: &str, label: &str) -> Result<String, Fault> {
|
|
|
454
474
|
}
|
|
455
475
|
}
|
|
456
476
|
|
|
457
|
-
|
|
458
|
-
|
|
477
|
+
/// The same, naming the field on the `needs-ui` line so a host can title its
|
|
478
|
+
/// own dialog and send the value back as `--secret NAME=VALUE`.
|
|
479
|
+
/// The same, but when no window can open the `needs-ui` line names the field,
|
|
480
|
+
/// so a host can title its own dialog and send the answer back as `--secret`.
|
|
481
|
+
/// The field is reported in the error's text, which the host reads after the
|
|
482
|
+
/// `needs-ui: password` line.
|
|
483
|
+
fn ask_field_password(field: &str, title: &str, label: &str) -> Result<String, Fault> {
|
|
484
|
+
match dialog::prompt_secret(title, label) {
|
|
459
485
|
Answer::Value(value) => Ok(value),
|
|
460
|
-
Answer::Cancelled => Err(Fault::Denied("cancelled".into())),
|
|
461
|
-
Answer::NoUi => Err(Fault::
|
|
486
|
+
Answer::Cancelled => Err(Fault::Denied("cancelled: no password entered".into())),
|
|
487
|
+
Answer::NoUi => Err(Fault::NeedsUiField(field.to_string())),
|
|
462
488
|
}
|
|
463
489
|
}
|
|
464
490
|
|
|
@@ -501,7 +527,7 @@ fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
|
|
|
501
527
|
/// and is treated like a human caller until it has a secret to sign with.
|
|
502
528
|
/// This keeps a half-configured host from getting a session it can neither
|
|
503
529
|
/// verify nor relay for.
|
|
504
|
-
fn
|
|
530
|
+
fn secret_kind_label(kind: Kind) -> &'static str {
|
|
505
531
|
match kind {
|
|
506
532
|
Kind::Bitwarden => "bitwarden",
|
|
507
533
|
Kind::Ente => "ente",
|
|
@@ -590,7 +616,7 @@ fn rekey(paths: &Paths, out: &Out, password_stdin: bool) -> Outcome {
|
|
|
590
616
|
let password = if password_stdin {
|
|
591
617
|
read_password()?
|
|
592
618
|
} else {
|
|
593
|
-
ask_password("ai-vault · 升级密钥参数", "主密码")?
|
|
619
|
+
ask_password(tr("ai-vault · upgrade key parameters", "ai-vault · 升级密钥参数"), tr("master password", "主密码"))?
|
|
594
620
|
};
|
|
595
621
|
let (items, _old_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
596
622
|
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
@@ -659,11 +685,11 @@ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_mi
|
|
|
659
685
|
let password = if password_stdin {
|
|
660
686
|
read_password()?
|
|
661
687
|
} else {
|
|
662
|
-
let first = ask_password("ai-vault · 创建主密码", "至少 8 位")?;
|
|
688
|
+
let first = ask_password(tr("ai-vault · set master password", "ai-vault · 创建主密码"), tr("at least 8 characters", "至少 8 位"))?;
|
|
663
689
|
if first.len() < 8 {
|
|
664
690
|
return Err(Fault::Usage("the master password must be at least 8 characters".into()));
|
|
665
691
|
}
|
|
666
|
-
let again = ask_password("ai-vault · 确认主密码", "再输入一次")?;
|
|
692
|
+
let again = ask_password(tr("ai-vault · confirm master password", "ai-vault · 确认主密码"), tr("type it again", "再输入一次"))?;
|
|
667
693
|
if again != first {
|
|
668
694
|
return Err(Fault::Denied("the two passwords do not match".into()));
|
|
669
695
|
}
|
|
@@ -714,7 +740,7 @@ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_
|
|
|
714
740
|
let password = if password_stdin {
|
|
715
741
|
read_password()?
|
|
716
742
|
} else {
|
|
717
|
-
ask_password("ai-vault · 解锁", "本地库主密码")?
|
|
743
|
+
ask_password(tr("ai-vault · unlock", "ai-vault · 解锁"), tr("local store master password", "本地库主密码"))?
|
|
718
744
|
};
|
|
719
745
|
let (items, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
720
746
|
crypto::OpenError::WrongPassword => {
|
|
@@ -794,29 +820,30 @@ fn settings_value(config: &config::Config, paths: &Paths) -> serde_json::Value {
|
|
|
794
820
|
}
|
|
795
821
|
|
|
796
822
|
fn settings_human(config: &config::Config, paths: &Paths) -> String {
|
|
823
|
+
let yes_no = |yes: bool| tr(if yes { "yes" } else { "no" }, if yes { "有" } else { "无" });
|
|
797
824
|
[
|
|
798
825
|
format!("vault.unlock: {} (never | time | session)", config.unlock.mode.as_str()),
|
|
799
|
-
format!("vault.hours: {}
|
|
800
|
-
format!(
|
|
801
|
-
"vault 机器级会话: {}",
|
|
802
|
-
if paths.auto_session().exists() { "有(免密)" } else { "无" }
|
|
803
|
-
),
|
|
826
|
+
format!("vault.hours: {}{}", config.unlock.hours, tr(" (time mode)", " (time 模式)")),
|
|
827
|
+
format!("{} {}", tr("vault machine-wide session:", "vault 机器级会话:"), if paths.auto_session().exists() { tr("yes (no password)", "有(免密)") } else { tr("no", "无") }),
|
|
804
828
|
format!("bitwarden.unlock: {} (never | time | session)", config.bitwarden.store.unlock.as_str()),
|
|
805
829
|
format!("bitwarden.hours: {}", config.bitwarden.store.hours),
|
|
806
830
|
format!("bitwarden.import: {} (ask | always | never)", config.bitwarden.import.as_str()),
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
format!("ente 已落盘的密钥: {}", if sealed::load(paths, Kind::Ente).ok().flatten().is_some() { "有" } else { "无" }),
|
|
810
|
-
format!(
|
|
811
|
-
"bitwarden 已落盘的会话: {}",
|
|
812
|
-
match sealed::load(paths, Kind::Bitwarden).ok().flatten() {
|
|
831
|
+
{
|
|
832
|
+
let bw = match sealed::load(paths, Kind::Bitwarden).ok().flatten() {
|
|
813
833
|
Some(saved) => match saved.expires_at {
|
|
814
|
-
Some(at) =>
|
|
815
|
-
|
|
834
|
+
Some(at) => tr_owned(
|
|
835
|
+
format!("yes (expires in {} min)", ((at - session::now_ms()) / 60_000).max(0)),
|
|
836
|
+
format!("有({} 分钟后过期)", ((at - session::now_ms()) / 60_000).max(0)),
|
|
837
|
+
),
|
|
838
|
+
None => tr("yes (no expiry)", "有(不过期)").to_string(),
|
|
816
839
|
},
|
|
817
|
-
None => "无".to_string(),
|
|
818
|
-
}
|
|
819
|
-
|
|
840
|
+
None => tr("no", "无").to_string(),
|
|
841
|
+
};
|
|
842
|
+
format!("{} {}", tr("bitwarden persisted session:", "bitwarden 已落盘的会话:"), bw)
|
|
843
|
+
},
|
|
844
|
+
format!("ente.unlock: {} (never | time | session)", config.ente.unlock.as_str()),
|
|
845
|
+
format!("ente.hours: {}", config.ente.hours),
|
|
846
|
+
format!("{} {}", tr("ente persisted key:", "ente 已落盘的密钥:"), yes_no(sealed::load(paths, Kind::Ente).ok().flatten().is_some())),
|
|
820
847
|
]
|
|
821
848
|
.join("\n")
|
|
822
849
|
}
|
|
@@ -865,7 +892,7 @@ fn settings(
|
|
|
865
892
|
let password = if password_stdin {
|
|
866
893
|
read_password()?
|
|
867
894
|
} else {
|
|
868
|
-
ask_password("ai-vault · 主密码", "切换解锁模式")?
|
|
895
|
+
ask_password(tr("ai-vault · master password", "ai-vault · 主密码"), tr("switching the unlock policy", "切换解锁模式"))?
|
|
869
896
|
};
|
|
870
897
|
let (_, vault_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
871
898
|
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
@@ -962,9 +989,9 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
|
|
|
962
989
|
match action.trim() {
|
|
963
990
|
"" | "get" => {
|
|
964
991
|
let stored = sealed::load(paths, kind)?
|
|
965
|
-
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret — save one first",
|
|
992
|
+
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret — save one first", secret_kind_label(kind))))?;
|
|
966
993
|
let key = sealed::key(paths, kind)?
|
|
967
|
-
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret",
|
|
994
|
+
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret", secret_kind_label(kind))))?;
|
|
968
995
|
out.value(
|
|
969
996
|
json!({ "ok": true, "key": key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
|
|
970
997
|
|| key,
|
|
@@ -977,7 +1004,7 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
|
|
|
977
1004
|
return Err(Fault::Usage("bw-session put expects the session key on stdin".into()));
|
|
978
1005
|
}
|
|
979
1006
|
let expires_at = sealed::save(paths, kind, &key)?;
|
|
980
|
-
audit::append(&paths.audit(), "cli", "sealed", None, Some(
|
|
1007
|
+
audit::append(&paths.audit(), "cli", "sealed", None, Some(secret_kind_label(kind)));
|
|
981
1008
|
out.value(json!({ "ok": true, "expiresAt": expires_at }), || {
|
|
982
1009
|
match expires_at {
|
|
983
1010
|
Some(at) => format!("saved (expires in {} min)", ((at - session::now_ms()) / 60_000).max(0)),
|
|
@@ -988,7 +1015,7 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
|
|
|
988
1015
|
}
|
|
989
1016
|
"clear" | "delete" => {
|
|
990
1017
|
let removed = sealed::clear(paths, kind);
|
|
991
|
-
audit::append(&paths.audit(), "cli", "sealed", None, Some(
|
|
1018
|
+
audit::append(&paths.audit(), "cli", "sealed", None, Some(secret_kind_label(kind)));
|
|
992
1019
|
out.value(json!({ "ok": true, "removed": removed }), || {
|
|
993
1020
|
if removed { "cleared".to_string() } else { "nothing stored".to_string() }
|
|
994
1021
|
});
|
|
@@ -1088,7 +1115,15 @@ fn list(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
|
|
|
1088
1115
|
}
|
|
1089
1116
|
items
|
|
1090
1117
|
.iter()
|
|
1091
|
-
.map(|i|
|
|
1118
|
+
.map(|i| {
|
|
1119
|
+
format!(
|
|
1120
|
+
"{}\t{}\t{}\t{}",
|
|
1121
|
+
i.name,
|
|
1122
|
+
kind_label(i.r#type),
|
|
1123
|
+
i.username.clone().unwrap_or_default(),
|
|
1124
|
+
i.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default()
|
|
1125
|
+
)
|
|
1126
|
+
})
|
|
1092
1127
|
.collect::<Vec<_>>()
|
|
1093
1128
|
.join("\n")
|
|
1094
1129
|
});
|
|
@@ -1124,10 +1159,17 @@ fn get(
|
|
|
1124
1159
|
// The window is what the user approves: no caller-supplied text may
|
|
1125
1160
|
// break out of its own line here.
|
|
1126
1161
|
let message = format!(
|
|
1127
|
-
"
|
|
1128
|
-
|
|
1162
|
+
"{} {}\n{} {}\n{} {}\n\n{}",
|
|
1163
|
+
tr("Entry:", "条目:"),
|
|
1164
|
+
format!("{} ({})", dialog::for_dialog(&item.name, 80), kind_label(item.r#type)),
|
|
1165
|
+
tr("Requester:", "请求方:"),
|
|
1129
1166
|
dialog::for_dialog(&session.requester, 40),
|
|
1130
|
-
|
|
1167
|
+
tr("Reason:", "原因:"),
|
|
1168
|
+
dialog::for_dialog(reason.unwrap_or(&tr("(none given)", "(未说明)").to_string()), 120),
|
|
1169
|
+
tr(
|
|
1170
|
+
"Allowing lets the same requester read it again for 5 minutes. The password enters the conversation.",
|
|
1171
|
+
"允许后 5 分钟内同一请求方可再次读取。密码会进入对话。"
|
|
1172
|
+
)
|
|
1131
1173
|
);
|
|
1132
1174
|
let approved = if answer_stdin {
|
|
1133
1175
|
// Relaying an answer is a host privilege: it must be signed with the
|
|
@@ -1148,7 +1190,7 @@ fn get(
|
|
|
1148
1190
|
}
|
|
1149
1191
|
answer
|
|
1150
1192
|
} else {
|
|
1151
|
-
match dialog::confirm("ai-vault · 读取本地密码", &message) {
|
|
1193
|
+
match dialog::confirm(tr("ai-vault · read local password", "ai-vault · 读取本地密码"), &message) {
|
|
1152
1194
|
Answer::Value(ok) => ok,
|
|
1153
1195
|
Answer::Cancelled => false,
|
|
1154
1196
|
Answer::NoUi => {
|
|
@@ -1187,97 +1229,264 @@ fn get(
|
|
|
1187
1229
|
|
|
1188
1230
|
struct AddRequest {
|
|
1189
1231
|
name: String,
|
|
1232
|
+
r#type: Option<String>,
|
|
1190
1233
|
username: Option<String>,
|
|
1191
1234
|
uri: Option<String>,
|
|
1192
1235
|
notes: Option<String>,
|
|
1236
|
+
fields: Vec<String>,
|
|
1237
|
+
secrets: Vec<String>,
|
|
1193
1238
|
password_stdin: bool,
|
|
1194
1239
|
yes: bool,
|
|
1195
1240
|
}
|
|
1196
1241
|
|
|
1242
|
+
/// Parse a type name the way a human writes it: login, note, secure-note,
|
|
1243
|
+
/// ssh key, "SSH key", drivers licence …
|
|
1244
|
+
fn parse_item_type(raw: &str) -> Option<ItemType> {
|
|
1245
|
+
let key: String = raw.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase();
|
|
1246
|
+
Some(match key.as_str() {
|
|
1247
|
+
"login" | "password" | "" => ItemType::Login,
|
|
1248
|
+
"note" | "securenote" => ItemType::SecureNote,
|
|
1249
|
+
"card" | "creditcard" => ItemType::Card,
|
|
1250
|
+
"identity" | "person" => ItemType::Identity,
|
|
1251
|
+
"sshkey" | "ssh" | "key" => ItemType::SshKey,
|
|
1252
|
+
"bankaccount" | "bank" => ItemType::BankAccount,
|
|
1253
|
+
"driverslicense" | "driverlicense" | "license" | "drivinglicence" => ItemType::DriversLicense,
|
|
1254
|
+
"passport" => ItemType::Passport,
|
|
1255
|
+
_ => return None,
|
|
1256
|
+
})
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1197
1259
|
fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outcome {
|
|
1198
1260
|
let mut session = load_session(paths, token.as_deref())?;
|
|
1199
1261
|
let name = req.name.trim().to_string();
|
|
1200
1262
|
if name.is_empty() {
|
|
1201
1263
|
return Err(Fault::Usage("an entry needs a name".into()));
|
|
1202
1264
|
}
|
|
1265
|
+
let kind = match req.r#type.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
|
|
1266
|
+
None => ItemType::Login,
|
|
1267
|
+
Some(raw) => parse_item_type(raw).ok_or_else(|| {
|
|
1268
|
+
Fault::Usage(format!(
|
|
1269
|
+
"unknown type \"{raw}\" — login, note, card, identity, sshkey, bankaccount, driverslicense, passport"
|
|
1270
|
+
))
|
|
1271
|
+
})?,
|
|
1272
|
+
};
|
|
1203
1273
|
let store = open_store(paths)?;
|
|
1204
1274
|
let items = items_with(&session, &store)?;
|
|
1205
1275
|
let existing = store::find(&items, &name).cloned();
|
|
1276
|
+
// Updating an entry of another type replaces its data block: say so in the window.
|
|
1277
|
+
let type_changes = existing.as_ref().is_some_and(|item| item.r#type != kind);
|
|
1278
|
+
|
|
1279
|
+
// --field NAME=VALUE pairs, by the type's own field names.
|
|
1280
|
+
let mut data: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
|
|
1281
|
+
let mut to_type: Vec<String> = Vec::new();
|
|
1282
|
+
for raw in &req.fields {
|
|
1283
|
+
let (field, value) = match raw.split_once('=') {
|
|
1284
|
+
Some((f, v)) => (f.trim().to_string(), Some(v.to_string())),
|
|
1285
|
+
None => (raw.trim().to_string(), None),
|
|
1286
|
+
};
|
|
1287
|
+
let field = resolve_field_name(kind, &field)
|
|
1288
|
+
.ok_or_else(|| Fault::Usage(format!("\"{field}\" is not a field of a {}", kind_label(kind))))?;
|
|
1289
|
+
match value {
|
|
1290
|
+
Some(v) => {
|
|
1291
|
+
data.insert(field, serde_json::Value::String(v));
|
|
1292
|
+
}
|
|
1293
|
+
None => to_type.push(field),
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
// Host-supplied hidden fields (the host asked the user in its own UI).
|
|
1297
|
+
for raw in &req.secrets {
|
|
1298
|
+
let (field, value) = raw.split_once('=').ok_or_else(|| Fault::Usage("--secret expects NAME=VALUE".into()))?;
|
|
1299
|
+
let field = resolve_field_name(kind, field.trim())
|
|
1300
|
+
.ok_or_else(|| Fault::Usage(format!("\"{}\" is not a field of a {}", field.trim(), kind_label(kind))))?;
|
|
1301
|
+
if !is_secret_field(kind, &field) {
|
|
1302
|
+
return Err(Fault::Usage(format!("--secret is for hidden fields; \"{field}\" can go in --field")));
|
|
1303
|
+
}
|
|
1304
|
+
data.insert(field, serde_json::Value::String(value.to_string()));
|
|
1305
|
+
}
|
|
1306
|
+
// The conventional flags feed the login fields and the shared notes.
|
|
1307
|
+
if kind == ItemType::Login {
|
|
1308
|
+
if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
1309
|
+
data.insert("username".into(), serde_json::Value::String(user.to_string()));
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
let notes = req.notes.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
|
|
1206
1313
|
|
|
1207
1314
|
if !req.yes {
|
|
1208
1315
|
let mut meta = Vec::new();
|
|
1316
|
+
let shown = dialog::for_dialog(&name, 80);
|
|
1317
|
+
let action = match &existing {
|
|
1318
|
+
Some(_) if type_changes => tr_owned(
|
|
1319
|
+
format!("Replace \"{shown}\" with a {} entry.", kind_label(kind)),
|
|
1320
|
+
format!("把「{shown}」改成{}条目。", kind_label(kind)),
|
|
1321
|
+
),
|
|
1322
|
+
Some(_) => tr_owned(format!("Update the existing entry \"{shown}\"."), format!("更新已有条目「{shown}」。")),
|
|
1323
|
+
None => tr_owned(format!("Create a {} entry \"{shown}\".", kind_label(kind)), format!("新建{}条目「{shown}」。", kind_label(kind))),
|
|
1324
|
+
};
|
|
1325
|
+
for (field, value) in &data {
|
|
1326
|
+
let secret = is_secret_field(kind, field);
|
|
1327
|
+
meta.push(format!(
|
|
1328
|
+
"{} {}",
|
|
1329
|
+
field,
|
|
1330
|
+
if secret { "••••".to_string() } else { dialog::for_dialog(value.as_str().unwrap_or(""), 120) }
|
|
1331
|
+
));
|
|
1332
|
+
}
|
|
1333
|
+
for field in &to_type {
|
|
1334
|
+
meta.push(format!("{field} ••••"));
|
|
1335
|
+
}
|
|
1209
1336
|
if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
1210
|
-
|
|
1337
|
+
if kind != ItemType::Login {
|
|
1338
|
+
meta.push(format!("{} {}", tr("Username:", "用户名:"), dialog::for_dialog(user, 60)));
|
|
1339
|
+
}
|
|
1211
1340
|
}
|
|
1212
1341
|
if let Some(uri) = req.uri.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
1213
1342
|
meta.push(format!("URI: {}", dialog::for_dialog(uri, 120)));
|
|
1214
1343
|
}
|
|
1215
|
-
if let Some(notes) =
|
|
1216
|
-
meta.push(format!("
|
|
1344
|
+
if let Some(notes) = notes.as_deref() {
|
|
1345
|
+
meta.push(format!("{} {}", tr("Notes:", "备注:"), dialog::for_dialog(notes, 120)));
|
|
1217
1346
|
}
|
|
1218
|
-
let shown = dialog::for_dialog(&name, 80);
|
|
1219
|
-
let action = if existing.is_some() {
|
|
1220
|
-
format!("更新已有条目「{shown}」。")
|
|
1221
|
-
} else {
|
|
1222
|
-
format!("新建条目「{shown}」。")
|
|
1223
|
-
};
|
|
1224
1347
|
let message = format!(
|
|
1225
|
-
"{action}{}\n
|
|
1226
|
-
if meta.is_empty() { String::new() } else { format!("\n{}", meta.join("\n")) }
|
|
1348
|
+
"{action}{}\n{}",
|
|
1349
|
+
if meta.is_empty() { String::new() } else { format!("\n{}", meta.join("\n")) },
|
|
1350
|
+
tr(
|
|
1351
|
+
"A window opens next for each hidden field. Nothing enters the conversation.",
|
|
1352
|
+
"接下来每个隐藏字段弹一个窗口。密码不会进入对话。"
|
|
1353
|
+
)
|
|
1227
1354
|
);
|
|
1228
|
-
match dialog::confirm("ai-vault · 保存到本地库", &message) {
|
|
1355
|
+
match dialog::confirm(tr("ai-vault · save to local store", "ai-vault · 保存到本地库"), &message) {
|
|
1229
1356
|
Answer::Value(true) => {}
|
|
1230
1357
|
Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied(format!("user denied saving \"{name}\""))),
|
|
1231
1358
|
Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
|
|
1232
1359
|
}
|
|
1233
1360
|
}
|
|
1234
1361
|
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1362
|
+
// Hidden fields: typed in a dialog (or read from stdin for the primary one).
|
|
1363
|
+
// On an update, a secret the caller did not mention is left as stored; only
|
|
1364
|
+
// a new entry (or a type change) needs every secret typed.
|
|
1365
|
+
let primary = kind.primary_field();
|
|
1366
|
+
let fresh = existing.as_ref().map_or(true, |item| item.r#type != kind);
|
|
1367
|
+
let mut secret_fields: Vec<String> = to_type;
|
|
1368
|
+
if fresh {
|
|
1369
|
+
if let Some(field) = primary {
|
|
1370
|
+
if !data.contains_key(field) {
|
|
1371
|
+
secret_fields.push(field.to_string());
|
|
1372
|
+
}
|
|
1244
1373
|
}
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1374
|
+
} else if let Some(item) = &existing {
|
|
1375
|
+
// Carry over the stored data block so `apply` does not read the absent
|
|
1376
|
+
// fields as "clear"; the draft's own values still win.
|
|
1377
|
+
for (field, value) in item.data.clone().unwrap_or_default() {
|
|
1378
|
+
data.entry(field).or_insert(value);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
for field in secret_fields {
|
|
1382
|
+
let password = if req.password_stdin && Some(field.as_str()) == primary {
|
|
1383
|
+
read_password()?
|
|
1384
|
+
} else {
|
|
1385
|
+
ask_field_password(&field, tr("ai-vault · password", "ai-vault · 密码"), &format!("{name} · {field}"))?
|
|
1386
|
+
};
|
|
1387
|
+
if password.is_empty() {
|
|
1388
|
+
return Err(Fault::Denied("cancelled: no password entered".into()));
|
|
1389
|
+
}
|
|
1390
|
+
data.insert(field, serde_json::Value::String(password));
|
|
1391
|
+
}
|
|
1392
|
+
if kind == ItemType::SecureNote && notes.is_none() && data.is_empty() {
|
|
1393
|
+
// A secure note is its notes; a dialog for the body when none was given.
|
|
1394
|
+
let body = match dialog::prompt_text(tr("ai-vault · note", "ai-vault · 备注"), tr("the note's contents", "备注内容")) {
|
|
1395
|
+
Answer::Value(text) => text,
|
|
1396
|
+
Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
|
|
1397
|
+
Answer::NoUi => return Err(Fault::NeedsUi("text")),
|
|
1398
|
+
};
|
|
1399
|
+
if body.trim().is_empty() {
|
|
1400
|
+
return Err(Fault::Usage("a note needs contents (--notes)".into()));
|
|
1401
|
+
}
|
|
1402
|
+
let notes = Some(body);
|
|
1403
|
+
return finish_add(paths, out, &mut session, Draft {
|
|
1404
|
+
name: name.clone(),
|
|
1405
|
+
r#type: kind,
|
|
1406
|
+
notes,
|
|
1407
|
+
data: None,
|
|
1408
|
+
..Default::default()
|
|
1409
|
+
}, &name);
|
|
1253
1410
|
}
|
|
1254
1411
|
|
|
1255
|
-
let
|
|
1256
|
-
let uri = req.uri.map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
|
|
1257
|
-
let notes = req.notes.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
|
|
1412
|
+
let uris = req.uri.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()).map(|u| vec![u]);
|
|
1258
1413
|
let draft = Draft {
|
|
1259
|
-
id: None,
|
|
1260
1414
|
name: name.clone(),
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1415
|
+
r#type: kind,
|
|
1416
|
+
username: if kind == ItemType::Login { req.username.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()) } else { None },
|
|
1417
|
+
password: String::new(),
|
|
1418
|
+
uris,
|
|
1419
|
+
data: if data.is_empty() { None } else { Some(data) },
|
|
1264
1420
|
notes,
|
|
1265
|
-
|
|
1421
|
+
..Default::default()
|
|
1266
1422
|
};
|
|
1423
|
+
finish_add(paths, out, &mut session, draft, &name)
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
fn finish_add(paths: &Paths, out: &Out, session: &mut Session, draft: Draft, name: &str) -> Outcome {
|
|
1267
1427
|
let mut inserted = false;
|
|
1268
|
-
|
|
1428
|
+
let kind = draft.r#type;
|
|
1429
|
+
mutate(paths, session, |items, now| {
|
|
1269
1430
|
inserted = store::apply(items, draft, now);
|
|
1270
1431
|
Ok(())
|
|
1271
1432
|
})?;
|
|
1272
1433
|
session.last_active = session::now_ms();
|
|
1273
|
-
persist(paths,
|
|
1274
|
-
audit::append(&paths.audit(), &session.requester, "add", Some(
|
|
1275
|
-
|
|
1276
|
-
|
|
1434
|
+
persist(paths, session);
|
|
1435
|
+
audit::append(&paths.audit(), &session.requester, "add", Some(name), Some(kind_label(kind)));
|
|
1436
|
+
let mut value = json!({ "ok": true, "item": name, "type": kind_label(kind), "created": inserted });
|
|
1437
|
+
if let Some(record) = value.as_object_mut() {
|
|
1438
|
+
record.insert("fields".into(), json!(kind.fields()));
|
|
1439
|
+
}
|
|
1440
|
+
out.value(value, || {
|
|
1441
|
+
format!(
|
|
1442
|
+
"saved \"{name}\" as a {} (hidden fields typed in the dialog, not shown)",
|
|
1443
|
+
kind_label(kind)
|
|
1444
|
+
)
|
|
1277
1445
|
});
|
|
1278
1446
|
Ok(())
|
|
1279
1447
|
}
|
|
1280
1448
|
|
|
1449
|
+
/// A type's field by the name a human typed (case- and separator-insensitive).
|
|
1450
|
+
fn resolve_field_name(kind: ItemType, raw: &str) -> Option<String> {
|
|
1451
|
+
let key: String = raw.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase();
|
|
1452
|
+
kind.fields()
|
|
1453
|
+
.iter()
|
|
1454
|
+
.find(|f| f.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase() == key)
|
|
1455
|
+
.map(|f| f.to_string())
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
/// Fields whose value must never be printed in a window or in `list`.
|
|
1459
|
+
pub(crate) fn is_secret_field(kind: ItemType, field: &str) -> bool {
|
|
1460
|
+
matches!(
|
|
1461
|
+
(kind, field),
|
|
1462
|
+
(_, "password")
|
|
1463
|
+
| (_, "privateKey")
|
|
1464
|
+
| (ItemType::Card, "code")
|
|
1465
|
+
| (ItemType::Card, "number")
|
|
1466
|
+
| (ItemType::BankAccount, "pin")
|
|
1467
|
+
| (ItemType::BankAccount, "accountNumber")
|
|
1468
|
+
| (ItemType::BankAccount, "routingNumber")
|
|
1469
|
+
| (_, "ssn")
|
|
1470
|
+
| (_, "licenseNumber")
|
|
1471
|
+
| (_, "passportNumber")
|
|
1472
|
+
| (ItemType::Passport, "nationalIdentificationNumber")
|
|
1473
|
+
| (_, "totp")
|
|
1474
|
+
)
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
fn kind_label(kind: ItemType) -> &'static str {
|
|
1478
|
+
match kind {
|
|
1479
|
+
ItemType::Login => "login",
|
|
1480
|
+
ItemType::SecureNote => "note",
|
|
1481
|
+
ItemType::Card => "card",
|
|
1482
|
+
ItemType::Identity => "identity",
|
|
1483
|
+
ItemType::SshKey => "SSH key",
|
|
1484
|
+
ItemType::BankAccount => "bank account",
|
|
1485
|
+
ItemType::DriversLicense => "driver's licence",
|
|
1486
|
+
ItemType::Passport => "passport",
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1281
1490
|
fn save(paths: &Paths, out: &Out, token: Option<String>, file: Option<PathBuf>, yes: bool) -> Outcome {
|
|
1282
1491
|
if !yes {
|
|
1283
1492
|
return Err(Fault::Usage("save needs --yes: the caller must confirm the write with the user".into()));
|
|
@@ -1317,7 +1526,7 @@ fn remove(paths: &Paths, out: &Out, token: Option<String>, name: &str, yes: bool
|
|
|
1317
1526
|
return Err(Fault::Error(format!("no such entry: \"{name}\"")));
|
|
1318
1527
|
}
|
|
1319
1528
|
if !yes {
|
|
1320
|
-
match dialog::confirm("ai-vault · 删除条目", &format!("删除「{}」?删除后无法恢复。", dialog::for_dialog(name, 80))) {
|
|
1529
|
+
match dialog::confirm(tr("ai-vault · delete entry", "ai-vault · 删除条目"), &tr_owned(format!("Delete \"{}\"? This cannot be undone.", dialog::for_dialog(name, 80)), format!("删除「{}」?删除后无法恢复。", dialog::for_dialog(name, 80)))) {
|
|
1321
1530
|
Answer::Value(true) => {}
|
|
1322
1531
|
Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
|
|
1323
1532
|
Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
|
|
@@ -1349,7 +1558,7 @@ fn grant(paths: &Paths, out: &Out, token: Option<String>, name: &str, minutes: O
|
|
|
1349
1558
|
let password = if is_host() {
|
|
1350
1559
|
read_password()?
|
|
1351
1560
|
} else {
|
|
1352
|
-
ask_password("ai-vault · 授权读取", "主密码(给一条条目免确认读取)")?
|
|
1561
|
+
ask_password(tr("ai-vault · grant read", "ai-vault · 授权读取"), tr("master password (lets one entry be read without confirmation)", "主密码(给一条条目免确认读取)"))?
|
|
1353
1562
|
};
|
|
1354
1563
|
if let Err(e) = crypto::open_with_passphrase(&store, &password) {
|
|
1355
1564
|
return Err(match e {
|
|
@@ -1431,12 +1640,15 @@ fn import_file(paths: &Paths, out: &Out, token: Option<String>, file: &PathBuf,
|
|
|
1431
1640
|
})
|
|
1432
1641
|
.collect::<Vec<_>>()
|
|
1433
1642
|
.join("\n");
|
|
1434
|
-
let more = if drafts.len() > 15 { format!("\n… 还有 {} 条", drafts.len() - 15) } else { String::new() };
|
|
1643
|
+
let more = if drafts.len() > 15 { tr_owned(format!("\n… {} more", drafts.len() - 15), format!("\n… 还有 {} 条", drafts.len() - 15)) } else { String::new() };
|
|
1435
1644
|
let message = format!(
|
|
1436
|
-
"
|
|
1645
|
+
"{} {} {}\n\n{shown}{more}\n\n{}",
|
|
1646
|
+
tr("Matched", "匹配"),
|
|
1647
|
+
drafts.len(),
|
|
1648
|
+
tr("items. Login items with a password are written to the local encrypted store; same-name entries are updated. Import?", "条。其中带密码的登录项会写入本地加密库,同名条目会被更新。允许导入?"),
|
|
1437
1649
|
drafts.len()
|
|
1438
1650
|
);
|
|
1439
|
-
match dialog::confirm("ai-vault · 从 Bitwarden 导入", &message) {
|
|
1651
|
+
match dialog::confirm(tr("ai-vault · import from Bitwarden", "ai-vault · 从 Bitwarden 导入"), &message) {
|
|
1440
1652
|
Answer::Value(true) => {}
|
|
1441
1653
|
Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("user denied the Bitwarden import".into())),
|
|
1442
1654
|
Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
|