@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
|
@@ -87,9 +87,10 @@ mod mac {
|
|
|
87
87
|
|
|
88
88
|
pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
|
|
89
89
|
let script = format!(
|
|
90
|
-
"tell application \"System Events\" to display dialog \"{}\" with title \"{}\" default answer \"\" with hidden answer buttons {{\"
|
|
90
|
+
"tell application \"System Events\" to display dialog \"{}\" with title \"{}\" default answer \"\" with hidden answer buttons {{\"{}\", \"OK\"}} default button \"OK\" giving up after {}",
|
|
91
91
|
quote(label),
|
|
92
92
|
quote(title),
|
|
93
|
+
crate::i18n::tr("Cancel", "取消"),
|
|
93
94
|
DIALOG_SECONDS
|
|
94
95
|
);
|
|
95
96
|
let out = osascript(&script);
|
|
@@ -115,9 +116,10 @@ mod mac {
|
|
|
115
116
|
|
|
116
117
|
pub fn prompt_text(title: &str, label: &str) -> Answer<String> {
|
|
117
118
|
let script = format!(
|
|
118
|
-
"tell application \"System Events\" to display dialog \"{}\" with title \"{}\" default answer \"\" buttons {{\"
|
|
119
|
+
"tell application \"System Events\" to display dialog \"{}\" with title \"{}\" default answer \"\" buttons {{\"{}\", \"OK\"}} default button \"OK\" giving up after {}",
|
|
119
120
|
quote(label),
|
|
120
121
|
quote(title),
|
|
122
|
+
crate::i18n::tr("Cancel", "取消"),
|
|
121
123
|
DIALOG_SECONDS
|
|
122
124
|
);
|
|
123
125
|
let out = osascript(&script);
|
|
@@ -139,16 +141,20 @@ mod mac {
|
|
|
139
141
|
|
|
140
142
|
pub fn confirm(title: &str, message: &str) -> Answer<bool> {
|
|
141
143
|
let script = format!(
|
|
142
|
-
"tell application \"System Events\" to display dialog \"{}\" with title \"{}\" buttons {{\"
|
|
144
|
+
"tell application \"System Events\" to display dialog \"{}\" with title \"{}\" buttons {{\"{}\", \"{}\"}} default button \"{}\" giving up after {}",
|
|
143
145
|
quote(message),
|
|
144
146
|
quote(title),
|
|
147
|
+
crate::i18n::tr("Deny", "拒绝"),
|
|
148
|
+
crate::i18n::tr("Allow", "允许"),
|
|
149
|
+
crate::i18n::tr("Deny", "拒绝"),
|
|
145
150
|
DIALOG_SECONDS
|
|
146
151
|
);
|
|
147
152
|
let out = osascript(&script);
|
|
148
153
|
if failed(&out) {
|
|
149
154
|
return Answer::NoUi;
|
|
150
155
|
}
|
|
151
|
-
|
|
156
|
+
let allow = crate::i18n::tr("Allow", "允许");
|
|
157
|
+
Answer::Value(out.code == 0 && out.stdout.contains(&format!("button returned:{allow}")))
|
|
152
158
|
}
|
|
153
159
|
}
|
|
154
160
|
|
|
@@ -177,7 +183,7 @@ $f.Controls.Add($box)
|
|
|
177
183
|
$ok = New-Object System.Windows.Forms.Button
|
|
178
184
|
$ok.Text = 'OK'; $ok.DialogResult = 'OK'; $ok.Left = 280; $ok.Top = 115; $f.AcceptButton = $ok
|
|
179
185
|
$cancel = New-Object System.Windows.Forms.Button
|
|
180
|
-
$cancel.Text =
|
|
186
|
+
$cancel.Text = $env:AI_VAULT_DLG_CANCEL; $cancel.DialogResult = 'Cancel'; $cancel.Left = 370; $cancel.Top = 115; $f.CancelButton = $cancel
|
|
181
187
|
$f.Controls.Add($ok); $f.Controls.Add($cancel)
|
|
182
188
|
$f.Add_Shown({ $box.Focus() })
|
|
183
189
|
if ($f.ShowDialog() -eq 'OK') { [Console]::Out.Write($box.Text); exit 0 } else { exit 1 }
|
|
@@ -203,6 +209,7 @@ if ($r -eq 'Yes') { exit 0 } else { exit 1 }
|
|
|
203
209
|
.env("AI_VAULT_DLG_TITLE", title)
|
|
204
210
|
.env("AI_VAULT_DLG_TEXT", text)
|
|
205
211
|
.env("AI_VAULT_DLG_SECRET", if secret { "1" } else { "0" })
|
|
212
|
+
.env("AI_VAULT_DLG_CANCEL", crate::i18n::tr("Cancel", "取消"))
|
|
206
213
|
.stdin(Stdio::null())
|
|
207
214
|
.stdout(Stdio::piped())
|
|
208
215
|
.stderr(Stdio::piped());
|
|
@@ -497,8 +504,8 @@ fn confirm_zenity(title: &str, message: &str) -> Answer<bool> {
|
|
|
497
504
|
arg("--no-markup"),
|
|
498
505
|
arg("--width=520"),
|
|
499
506
|
arg("--default-cancel"),
|
|
500
|
-
arg("--ok-label
|
|
501
|
-
arg("--cancel-label
|
|
507
|
+
arg(format!("--ok-label={}", crate::i18n::tr("Allow", "允许"))),
|
|
508
|
+
arg(format!("--cancel-label={}", crate::i18n::tr("Deny", "拒绝"))),
|
|
502
509
|
timeout_arg(),
|
|
503
510
|
]);
|
|
504
511
|
if failed_to_open(&z) {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
//! User-facing strings, English by default, Chinese with `AI_VAULT_LANG=zh`
|
|
2
|
+
//! (or a `zh_*` locale). Rust-side texts: dialogs, prompts, notices, errors.
|
|
3
|
+
//!
|
|
4
|
+
//! The rule: a message that a human reads is English unless they asked for
|
|
5
|
+
//! Chinese. Strings that a *host* parses (exit codes, `needs-ui:`,
|
|
6
|
+
//! `no such entry`, the JSON keys) never change.
|
|
7
|
+
|
|
8
|
+
use std::sync::OnceLock;
|
|
9
|
+
|
|
10
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
11
|
+
pub enum Lang {
|
|
12
|
+
En,
|
|
13
|
+
Zh,
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
static LANG: OnceLock<Lang> = OnceLock::new();
|
|
17
|
+
|
|
18
|
+
pub fn lang() -> Lang {
|
|
19
|
+
*LANG.get_or_init(detect)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
fn detect() -> Lang {
|
|
23
|
+
let explicit = std::env::var("AI_VAULT_LANG").unwrap_or_default().to_lowercase();
|
|
24
|
+
if explicit.starts_with("zh") {
|
|
25
|
+
return Lang::Zh;
|
|
26
|
+
}
|
|
27
|
+
if explicit == "en" || !explicit.is_empty() {
|
|
28
|
+
return Lang::En;
|
|
29
|
+
}
|
|
30
|
+
let locale = ["LC_ALL", "LC_MESSAGES", "LANG"]
|
|
31
|
+
.iter()
|
|
32
|
+
.find_map(|name| std::env::var(name).ok())
|
|
33
|
+
.unwrap_or_default()
|
|
34
|
+
.to_lowercase();
|
|
35
|
+
if locale.starts_with("zh") {
|
|
36
|
+
Lang::Zh
|
|
37
|
+
} else {
|
|
38
|
+
Lang::En
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// Pick the English or the Chinese text.
|
|
43
|
+
pub fn tr(en: &'static str, zh: &'static str) -> &'static str {
|
|
44
|
+
match lang() {
|
|
45
|
+
Lang::En => en,
|
|
46
|
+
Lang::Zh => zh,
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// The same with owned strings (formatted text).
|
|
51
|
+
pub fn tr_owned(en: String, zh: String) -> String {
|
|
52
|
+
match lang() {
|
|
53
|
+
Lang::En => en,
|
|
54
|
+
Lang::Zh => zh,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -3,21 +3,10 @@
|
|
|
3
3
|
|
|
4
4
|
use serde_json::Value;
|
|
5
5
|
|
|
6
|
-
use crate::store::{Draft, Source};
|
|
6
|
+
use crate::store::{Draft, Field, ItemType, Source};
|
|
7
7
|
|
|
8
8
|
const MAX_NAME: usize = 200;
|
|
9
9
|
|
|
10
|
-
fn as_uris(login: &serde_json::Map<String, Value>) -> Vec<String> {
|
|
11
|
-
match login.get("uris").and_then(|u| u.as_array()) {
|
|
12
|
-
Some(list) => list
|
|
13
|
-
.iter()
|
|
14
|
-
.filter_map(|entry| entry.get("uri").and_then(|u| u.as_str()))
|
|
15
|
-
.filter(|uri| !uri.is_empty())
|
|
16
|
-
.map(str::to_string)
|
|
17
|
-
.collect(),
|
|
18
|
-
None => Vec::new(),
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
10
|
|
|
22
11
|
fn sanitized_name(raw: &str) -> String {
|
|
23
12
|
let cleaned = raw.replace(['\r', '\n'], " ");
|
|
@@ -28,8 +17,10 @@ fn sanitized_name(raw: &str) -> String {
|
|
|
28
17
|
cleaned.chars().take(MAX_NAME).collect()
|
|
29
18
|
}
|
|
30
19
|
|
|
31
|
-
/// Bitwarden export (array or `{ "items": [...] }`) -> drafts
|
|
32
|
-
///
|
|
20
|
+
/// Bitwarden export (array or `{ "items": [...] }`) -> drafts, for every
|
|
21
|
+
/// item type, field for field. Login items without a password are still
|
|
22
|
+
/// imported (a PIN-only or passkey-only login is a login); a `name` is the
|
|
23
|
+
/// only thing an item must have. Names are sorted, then made unique with
|
|
33
24
|
/// `Name (2)`, `Name (3)`, … Each draft keeps its Bitwarden id so a re-import
|
|
34
25
|
/// updates the same row after a rename.
|
|
35
26
|
pub fn from_bitwarden(raw: &Value) -> Result<Vec<Draft>, String> {
|
|
@@ -50,34 +41,77 @@ pub fn from_bitwarden(raw: &Value) -> Result<Vec<Draft>, String> {
|
|
|
50
41
|
let mut drafts: Vec<Draft> = Vec::new();
|
|
51
42
|
for item in items {
|
|
52
43
|
let Some(rec) = item.as_object() else { continue };
|
|
53
|
-
let
|
|
54
|
-
|
|
55
|
-
if password.is_empty() {
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
let username = rec
|
|
59
|
-
.get("login")
|
|
60
|
-
.and_then(|l| l.get("username"))
|
|
61
|
-
.and_then(Value::as_str)
|
|
62
|
-
.filter(|u| !u.is_empty())
|
|
63
|
-
.map(str::to_string);
|
|
64
|
-
let notes = rec
|
|
65
|
-
.get("notes")
|
|
66
|
-
.and_then(Value::as_str)
|
|
67
|
-
.filter(|n| !n.is_empty())
|
|
68
|
-
.map(str::to_string);
|
|
44
|
+
let kind = ItemType::from_code(rec.get("type").and_then(Value::as_u64).unwrap_or(1) as u8)
|
|
45
|
+
.ok_or_else(|| format!("unsupported item type {}", rec.get("type").and_then(Value::as_u64).unwrap_or(0)))?;
|
|
69
46
|
let source = rec
|
|
70
47
|
.get("id")
|
|
71
48
|
.and_then(Value::as_str)
|
|
72
49
|
.filter(|id| !id.is_empty())
|
|
73
50
|
.map(|id| Source { kind: "bitwarden".into(), id: id.to_string() });
|
|
51
|
+
|
|
52
|
+
// The type's own block, by Bitwarden's key and field names; unknown
|
|
53
|
+
// keys are kept rather than dropped, so a newer CLI loses nothing.
|
|
54
|
+
let mut data = serde_json::Map::new();
|
|
55
|
+
if let Some(block) = rec.get(kind.data_key()).and_then(Value::as_object) {
|
|
56
|
+
for (field, value) in block {
|
|
57
|
+
if field == "uris" || field == "totp" && value.is_null() {
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
match value {
|
|
61
|
+
Value::String(text) if !text.is_empty() => {
|
|
62
|
+
data.insert(field.clone(), Value::String(text.clone()));
|
|
63
|
+
}
|
|
64
|
+
Value::Null => {}
|
|
65
|
+
other => {
|
|
66
|
+
data.insert(field.clone(), other.clone());
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
let uris = rec
|
|
72
|
+
.get(kind.data_key())
|
|
73
|
+
.and_then(|b| b.get("uris"))
|
|
74
|
+
.and_then(Value::as_array)
|
|
75
|
+
.map(|list| {
|
|
76
|
+
list.iter()
|
|
77
|
+
.filter_map(|entry| entry.get("uri").and_then(Value::as_str))
|
|
78
|
+
.filter(|uri| !uri.is_empty())
|
|
79
|
+
.map(str::to_string)
|
|
80
|
+
.collect::<Vec<_>>()
|
|
81
|
+
})
|
|
82
|
+
.filter(|list: &Vec<String>| !list.is_empty());
|
|
83
|
+
|
|
84
|
+
let fields = rec.get("fields").and_then(Value::as_array).map(|list| {
|
|
85
|
+
list.iter()
|
|
86
|
+
.filter_map(|f| f.as_object())
|
|
87
|
+
.map(|f| Field {
|
|
88
|
+
name: f.get("name").and_then(Value::as_str).unwrap_or("").to_string(),
|
|
89
|
+
value: f.get("value").and_then(Value::as_str).unwrap_or("").to_string(),
|
|
90
|
+
r#type: f.get("type").and_then(Value::as_u64).unwrap_or(0) as u8,
|
|
91
|
+
linked_id: f.get("linkedId").and_then(Value::as_u64).map(|n| n.to_string()),
|
|
92
|
+
})
|
|
93
|
+
.collect::<Vec<_>>()
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
let (username, password) = if kind == ItemType::Login {
|
|
97
|
+
(
|
|
98
|
+
data.get("username").and_then(Value::as_str).map(str::to_string),
|
|
99
|
+
data.get("password").and_then(Value::as_str).unwrap_or("").to_string(),
|
|
100
|
+
)
|
|
101
|
+
} else {
|
|
102
|
+
(None, String::new())
|
|
103
|
+
};
|
|
104
|
+
|
|
74
105
|
drafts.push(Draft {
|
|
75
106
|
id: None,
|
|
76
107
|
name: sanitized_name(rec.get("name").and_then(Value::as_str).unwrap_or("")),
|
|
108
|
+
r#type: kind,
|
|
77
109
|
username,
|
|
78
|
-
password
|
|
79
|
-
uris
|
|
80
|
-
|
|
110
|
+
password,
|
|
111
|
+
uris,
|
|
112
|
+
data: if data.is_empty() { None } else { Some(data) },
|
|
113
|
+
notes: rec.get("notes").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string),
|
|
114
|
+
fields: fields.filter(|f: &Vec<Field>| !f.is_empty()),
|
|
81
115
|
source,
|
|
82
116
|
});
|
|
83
117
|
}
|
|
@@ -86,16 +120,12 @@ pub fn from_bitwarden(raw: &Value) -> Result<Vec<Draft>, String> {
|
|
|
86
120
|
a.name
|
|
87
121
|
.to_lowercase()
|
|
88
122
|
.cmp(&b.name.to_lowercase())
|
|
123
|
+
.then_with(|| a.r#type.cmp(&b.r#type))
|
|
89
124
|
.then_with(|| a.username.clone().unwrap_or_default().to_lowercase().cmp(&b.username.clone().unwrap_or_default().to_lowercase()))
|
|
90
|
-
.then_with(|| {
|
|
91
|
-
let ax = a.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default().to_lowercase();
|
|
92
|
-
let bx = b.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default().to_lowercase();
|
|
93
|
-
ax.cmp(&bx)
|
|
94
|
-
})
|
|
95
125
|
});
|
|
96
|
-
let mut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
|
126
|
+
let mut seen: std::collections::HashMap<(String, ItemType), usize> = std::collections::HashMap::new();
|
|
97
127
|
for item in &mut drafts {
|
|
98
|
-
let count = seen.entry(item.name.to_lowercase()).or_insert(0);
|
|
128
|
+
let count = seen.entry((item.name.to_lowercase(), item.r#type)).or_insert(0);
|
|
99
129
|
*count += 1;
|
|
100
130
|
if *count > 1 {
|
|
101
131
|
item.name = format!("{} ({count})", item.name);
|
|
@@ -136,17 +166,24 @@ mod tests {
|
|
|
136
166
|
use super::*;
|
|
137
167
|
|
|
138
168
|
#[test]
|
|
139
|
-
fn
|
|
169
|
+
fn imports_every_item_including_passwordless_logins() {
|
|
140
170
|
let raw = serde_json::json!([
|
|
141
171
|
{ "id": "1", "name": "Good", "login": { "username": "u", "password": "p", "uris": [{ "uri": "https://a" }] } },
|
|
142
|
-
{ "id": "2", "name": "
|
|
143
|
-
{ "id": "3", "name": "
|
|
172
|
+
{ "id": "2", "name": "PasskeyOnly", "type": 1, "login": { "username": "u" } },
|
|
173
|
+
{ "id": "3", "name": "Just a note", "type": 2, "secureNote": {}, "notes": "x" }
|
|
144
174
|
]);
|
|
145
|
-
let drafts = from_bitwarden(&raw).unwrap();
|
|
146
|
-
|
|
147
|
-
assert_eq!(drafts
|
|
148
|
-
|
|
149
|
-
assert_eq!(
|
|
175
|
+
let mut drafts = from_bitwarden(&raw).unwrap();
|
|
176
|
+
drafts.sort_by(|a, b| a.name.cmp(&b.name));
|
|
177
|
+
assert_eq!(drafts.len(), 3, "a login without a password is still a login");
|
|
178
|
+
let good = drafts.iter().find(|d| d.name == "Good").unwrap();
|
|
179
|
+
assert_eq!(good.uris.as_ref().unwrap()[0], "https://a");
|
|
180
|
+
assert_eq!(good.source.as_ref().unwrap().id, "1");
|
|
181
|
+
let passkey = drafts.iter().find(|d| d.name == "PasskeyOnly").unwrap();
|
|
182
|
+
assert_eq!(passkey.r#type, ItemType::Login);
|
|
183
|
+
assert!(passkey.password.is_empty());
|
|
184
|
+
let note = drafts.iter().find(|d| d.name == "Just a note").unwrap();
|
|
185
|
+
assert_eq!(note.r#type, ItemType::SecureNote);
|
|
186
|
+
assert_eq!(note.notes.as_deref(), Some("x"));
|
|
150
187
|
}
|
|
151
188
|
|
|
152
189
|
#[test]
|
|
@@ -3,26 +3,142 @@
|
|
|
3
3
|
|
|
4
4
|
use serde::{Deserialize, Serialize};
|
|
5
5
|
|
|
6
|
+
/// The item types, numbered exactly as Bitwarden numbers them, so an import is
|
|
7
|
+
/// a copy and a manual entry is the same shape. `login` is what the store held
|
|
8
|
+
/// before types existed; a file without `type` is read as all-login.
|
|
9
|
+
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
|
10
|
+
#[serde(rename_all = "camelCase")]
|
|
11
|
+
pub enum ItemType {
|
|
12
|
+
#[default]
|
|
13
|
+
Login,
|
|
14
|
+
SecureNote,
|
|
15
|
+
Card,
|
|
16
|
+
Identity,
|
|
17
|
+
SshKey,
|
|
18
|
+
/// Behind Bitwarden's "new item types" flag; stored the same way.
|
|
19
|
+
BankAccount,
|
|
20
|
+
DriversLicense,
|
|
21
|
+
Passport,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
impl ItemType {
|
|
25
|
+
pub fn from_code(code: u8) -> Option<ItemType> {
|
|
26
|
+
Some(match code {
|
|
27
|
+
1 => ItemType::Login,
|
|
28
|
+
2 => ItemType::SecureNote,
|
|
29
|
+
3 => ItemType::Card,
|
|
30
|
+
4 => ItemType::Identity,
|
|
31
|
+
5 => ItemType::SshKey,
|
|
32
|
+
6 => ItemType::BankAccount,
|
|
33
|
+
7 => ItemType::DriversLicense,
|
|
34
|
+
8 => ItemType::Passport,
|
|
35
|
+
_ => return None,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// The key Bitwarden puts the type's own fields under.
|
|
40
|
+
pub fn data_key(self) -> &'static str {
|
|
41
|
+
match self {
|
|
42
|
+
ItemType::Login => "login",
|
|
43
|
+
ItemType::SecureNote => "secureNote",
|
|
44
|
+
ItemType::Card => "card",
|
|
45
|
+
ItemType::Identity => "identity",
|
|
46
|
+
ItemType::SshKey => "sshKey",
|
|
47
|
+
ItemType::BankAccount => "bankAccount",
|
|
48
|
+
ItemType::DriversLicense => "driversLicense",
|
|
49
|
+
ItemType::Passport => "passport",
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// Every field of this type, in Bitwarden's order. A secure note has none
|
|
54
|
+
/// of its own: its content is the item's `notes`.
|
|
55
|
+
pub fn fields(self) -> &'static [&'static str] {
|
|
56
|
+
match self {
|
|
57
|
+
ItemType::Login => &["username", "password", "totp"],
|
|
58
|
+
ItemType::SecureNote => &[],
|
|
59
|
+
ItemType::Card => &["cardholderName", "brand", "number", "expMonth", "expYear", "code"],
|
|
60
|
+
ItemType::Identity => &[
|
|
61
|
+
"title", "firstName", "middleName", "lastName", "address1", "address2", "address3", "city",
|
|
62
|
+
"state", "postalCode", "country", "company", "email", "phone", "ssn", "username",
|
|
63
|
+
"passportNumber", "licenseNumber",
|
|
64
|
+
],
|
|
65
|
+
ItemType::SshKey => &["privateKey", "publicKey", "keyFingerprint"],
|
|
66
|
+
ItemType::BankAccount => &[
|
|
67
|
+
"bankName", "nameOnAccount", "accountType", "accountNumber", "routingNumber",
|
|
68
|
+
"branchNumber", "pin", "swiftCode", "iban", "bankContactPhone",
|
|
69
|
+
],
|
|
70
|
+
ItemType::DriversLicense => &[
|
|
71
|
+
"firstName", "middleName", "lastName", "dateOfBirth", "licenseNumber", "issuingCountry",
|
|
72
|
+
"issuingState", "issueDate", "expirationDate", "issuingAuthority", "licenseClass",
|
|
73
|
+
],
|
|
74
|
+
ItemType::Passport => &[
|
|
75
|
+
"surname", "givenName", "dateOfBirth", "sex", "birthPlace", "nationality", "issuingCountry",
|
|
76
|
+
"passportNumber", "passportType", "nationalIdentificationNumber", "issuingAuthority",
|
|
77
|
+
"issueDate", "expirationDate",
|
|
78
|
+
],
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// The one field a human means by "the secret" of this type, when they
|
|
83
|
+
/// read one entry with `get` or add one by hand. The others are in `data`.
|
|
84
|
+
pub fn primary_field(self) -> Option<&'static str> {
|
|
85
|
+
match self {
|
|
86
|
+
ItemType::Login => Some("password"),
|
|
87
|
+
ItemType::Card => Some("code"),
|
|
88
|
+
ItemType::SshKey => Some("privateKey"),
|
|
89
|
+
ItemType::BankAccount => Some("pin"),
|
|
90
|
+
// A secure note's secret is its body; an identity's and a document's
|
|
91
|
+
// are spread over many fields, so there is no single one to pick.
|
|
92
|
+
_ => None,
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// A custom field, as Bitwarden stores it: 0 text, 1 hidden, 2 boolean, 3 linked.
|
|
98
|
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
|
99
|
+
#[serde(rename_all = "camelCase")]
|
|
100
|
+
pub struct Field {
|
|
101
|
+
pub name: String,
|
|
102
|
+
#[serde(default)]
|
|
103
|
+
pub value: String,
|
|
104
|
+
#[serde(default)]
|
|
105
|
+
pub r#type: u8,
|
|
106
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
107
|
+
pub linked_id: Option<String>,
|
|
108
|
+
}
|
|
109
|
+
|
|
6
110
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
|
7
111
|
pub struct Source {
|
|
8
112
|
pub kind: String,
|
|
9
113
|
pub id: String,
|
|
10
114
|
}
|
|
11
115
|
|
|
116
|
+
/// One entry. The top of the struct is Bitwarden's item envelope; the type's
|
|
117
|
+
/// own fields live in `data`, and `notes` / `fields` are shared by every type.
|
|
12
118
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
13
119
|
#[serde(rename_all = "camelCase")]
|
|
14
120
|
pub struct Item {
|
|
15
121
|
pub id: String,
|
|
16
122
|
pub name: String,
|
|
123
|
+
#[serde(default = "default_item_type")]
|
|
124
|
+
pub r#type: ItemType,
|
|
125
|
+
/// Login only, kept at the top level too so `vault_get` and the old
|
|
126
|
+
/// flat format agree; it mirrors `data.username`.
|
|
17
127
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
18
128
|
pub username: Option<String>,
|
|
129
|
+
/// Login only, same as `data.password`; empty for the other types.
|
|
19
130
|
#[serde(default)]
|
|
20
131
|
pub password: String,
|
|
21
132
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
22
133
|
pub uris: Option<Vec<String>>,
|
|
134
|
+
/// The type's own fields, by Bitwarden's names.
|
|
135
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
136
|
+
pub data: Option<serde_json::Map<String, serde_json::Value>>,
|
|
23
137
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
24
138
|
pub notes: Option<String>,
|
|
25
139
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
140
|
+
pub fields: Option<Vec<Field>>,
|
|
141
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
26
142
|
pub source: Option<Source>,
|
|
27
143
|
#[serde(rename = "createdAt")]
|
|
28
144
|
pub created_at: String,
|
|
@@ -30,28 +146,85 @@ pub struct Item {
|
|
|
30
146
|
pub updated_at: String,
|
|
31
147
|
}
|
|
32
148
|
|
|
33
|
-
|
|
149
|
+
fn default_item_type() -> ItemType {
|
|
150
|
+
ItemType::Login
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
impl Item {
|
|
154
|
+
/// Keep the flat login mirrors and the typed block in step.
|
|
155
|
+
pub fn sync_login_mirrors(&mut self) {
|
|
156
|
+
if self.r#type == ItemType::Login {
|
|
157
|
+
let data = self.data.get_or_insert_with(serde_json::Map::new);
|
|
158
|
+
if let Some(user) = &self.username {
|
|
159
|
+
data.insert("username".into(), serde_json::Value::String(user.clone()));
|
|
160
|
+
} else {
|
|
161
|
+
data.remove("username");
|
|
162
|
+
}
|
|
163
|
+
data.insert("password".into(), serde_json::Value::String(self.password.clone()));
|
|
164
|
+
} else {
|
|
165
|
+
self.username = None;
|
|
166
|
+
self.password = String::new();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// Metadata only: what `list` shows. Every secret is left out: passwords,
|
|
172
|
+
/// card numbers and codes, keys, PINs, SSNs, and the value of any custom
|
|
173
|
+
/// field marked hidden. A secure note shows no body (the body *is* the secret).
|
|
34
174
|
#[derive(Debug, Serialize)]
|
|
175
|
+
#[serde(rename_all = "camelCase")]
|
|
35
176
|
pub struct ItemSummary {
|
|
36
177
|
pub name: String,
|
|
178
|
+
#[serde(rename = "type")]
|
|
179
|
+
pub kind: ItemType,
|
|
180
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
37
181
|
pub username: Option<String>,
|
|
38
182
|
pub uris: Vec<String>,
|
|
183
|
+
/// Non-secret fields of the type, shown so a card or an identity can be
|
|
184
|
+
/// told apart in a listing (cardholder, brand, expiry; name, email…).
|
|
185
|
+
#[serde(default)]
|
|
186
|
+
pub fields: serde_json::Map<String, serde_json::Value>,
|
|
187
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
188
|
+
pub has_notes: Option<bool>,
|
|
39
189
|
#[serde(rename = "updatedAt")]
|
|
40
190
|
pub updated_at: String,
|
|
41
191
|
}
|
|
42
192
|
|
|
43
193
|
impl From<&Item> for ItemSummary {
|
|
44
194
|
fn from(item: &Item) -> Self {
|
|
195
|
+
let mut fields = serde_json::Map::new();
|
|
196
|
+
if let Some(data) = &item.data {
|
|
197
|
+
for (key, value) in data {
|
|
198
|
+
if !crate::cli::is_secret_field(item.r#type, key) && key != "username" && key != "password" {
|
|
199
|
+
if let Some(text) = value.as_str().filter(|t| !t.is_empty()) {
|
|
200
|
+
fields.insert(key.clone(), serde_json::Value::String(crate::dialog::for_dialog(text, 80)));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if let Some(custom) = &item.fields {
|
|
206
|
+
for field in custom {
|
|
207
|
+
// 1 = hidden in Bitwarden's field types
|
|
208
|
+
if field.r#type != 1 && !field.value.is_empty() {
|
|
209
|
+
fields.insert(field.name.clone(), serde_json::Value::String(crate::dialog::for_dialog(&field.value, 80)));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
45
213
|
ItemSummary {
|
|
46
214
|
name: item.name.clone(),
|
|
215
|
+
kind: item.r#type,
|
|
47
216
|
username: item.username.clone(),
|
|
48
217
|
uris: item.uris.clone().unwrap_or_default(),
|
|
218
|
+
fields,
|
|
219
|
+
has_notes: item.notes.as_ref().filter(|n| !n.is_empty()).map(|_| true),
|
|
49
220
|
updated_at: item.updated_at.clone(),
|
|
50
221
|
}
|
|
51
222
|
}
|
|
52
223
|
}
|
|
53
224
|
|
|
54
225
|
/// One entry to insert or merge, from `ai-vault add`, `save`, or an import.
|
|
226
|
+
/// The same envelope as [`Item`]; a missing `type` means a login, which is
|
|
227
|
+
/// also how files written before types existed are read.
|
|
55
228
|
#[derive(Debug, Clone, Default, Deserialize)]
|
|
56
229
|
#[serde(rename_all = "camelCase")]
|
|
57
230
|
pub struct Draft {
|
|
@@ -60,17 +233,50 @@ pub struct Draft {
|
|
|
60
233
|
#[serde(default)]
|
|
61
234
|
pub name: String,
|
|
62
235
|
#[serde(default)]
|
|
236
|
+
pub r#type: ItemType,
|
|
237
|
+
#[serde(default)]
|
|
63
238
|
pub username: Option<String>,
|
|
64
239
|
#[serde(default)]
|
|
65
240
|
pub password: String,
|
|
66
241
|
#[serde(default)]
|
|
67
242
|
pub uris: Option<Vec<String>>,
|
|
68
243
|
#[serde(default)]
|
|
244
|
+
pub data: Option<serde_json::Map<String, serde_json::Value>>,
|
|
245
|
+
#[serde(default)]
|
|
69
246
|
pub notes: Option<String>,
|
|
70
247
|
#[serde(default)]
|
|
248
|
+
pub fields: Option<Vec<Field>>,
|
|
249
|
+
#[serde(default)]
|
|
71
250
|
pub source: Option<Source>,
|
|
72
251
|
}
|
|
73
252
|
|
|
253
|
+
impl Draft {
|
|
254
|
+
/// Fill `data` from the flat login mirrors when a caller (the old `add`
|
|
255
|
+
/// path, an old JSON payload) gave only `username`/`password`.
|
|
256
|
+
pub fn normalise(mut self) -> Draft {
|
|
257
|
+
if self.r#type == ItemType::Login {
|
|
258
|
+
let data = self.data.get_or_insert_with(serde_json::Map::new);
|
|
259
|
+
if let Some(user) = &self.username {
|
|
260
|
+
data.entry("username").or_insert_with(|| serde_json::Value::String(user.clone()));
|
|
261
|
+
}
|
|
262
|
+
if !self.password.is_empty() {
|
|
263
|
+
data.insert("password".into(), serde_json::Value::String(self.password.clone()));
|
|
264
|
+
}
|
|
265
|
+
if let Some(password) = data.get("password").and_then(|v| v.as_str()) {
|
|
266
|
+
self.password = password.to_string();
|
|
267
|
+
}
|
|
268
|
+
if let Some(user) = data.get("username").and_then(|v| v.as_str()) {
|
|
269
|
+
self.username = Some(user.to_string());
|
|
270
|
+
}
|
|
271
|
+
} else {
|
|
272
|
+
// Only a login has the flat mirrors; for the rest the secret is in `data`.
|
|
273
|
+
self.username = None;
|
|
274
|
+
self.password = String::new();
|
|
275
|
+
}
|
|
276
|
+
self
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
74
280
|
pub fn now_iso() -> String {
|
|
75
281
|
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
|
|
76
282
|
}
|
|
@@ -100,6 +306,7 @@ pub fn remove(items: &mut Vec<Item>, name: &str) -> bool {
|
|
|
100
306
|
/// An entry is matched by local id, else by its import source, else by name.
|
|
101
307
|
/// Returns `true` when a new entry was pushed.
|
|
102
308
|
pub fn apply(items: &mut Vec<Item>, draft: Draft, now: &str) -> bool {
|
|
309
|
+
let draft = draft.normalise();
|
|
103
310
|
let lower = draft.name.to_lowercase();
|
|
104
311
|
let existing_idx = if let Some(id) = draft.id.as_deref() {
|
|
105
312
|
items.iter().position(|i| i.id == id)
|
|
@@ -120,10 +327,26 @@ pub fn apply(items: &mut Vec<Item>, draft: Draft, now: &str) -> bool {
|
|
|
120
327
|
&& items.iter().enumerate().any(|(i, other)| i != idx && other.name.to_lowercase() == lower);
|
|
121
328
|
let item = &mut items[idx];
|
|
122
329
|
item.name = draft.name.clone();
|
|
123
|
-
|
|
330
|
+
item.r#type = draft.r#type;
|
|
331
|
+
// A field the draft does not mention keeps its stored value; one it
|
|
332
|
+
// mentions as null clears it. An empty `password` means "unchanged".
|
|
333
|
+
if let Some(incoming) = draft.data {
|
|
334
|
+
let data = item.data.get_or_insert_with(serde_json::Map::new);
|
|
335
|
+
for (key, value) in incoming {
|
|
336
|
+
if key == "password" && value.as_str() == Some("") {
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if value.is_null() {
|
|
340
|
+
data.remove(&key);
|
|
341
|
+
} else {
|
|
342
|
+
data.insert(key, value);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if draft.username.is_some() || draft.r#type != ItemType::Login {
|
|
124
347
|
item.username = draft.username.clone();
|
|
125
348
|
}
|
|
126
|
-
if !draft.password.is_empty() {
|
|
349
|
+
if !draft.password.is_empty() || draft.r#type != ItemType::Login {
|
|
127
350
|
item.password = draft.password.clone();
|
|
128
351
|
}
|
|
129
352
|
if draft.uris.is_some() {
|
|
@@ -132,27 +355,36 @@ pub fn apply(items: &mut Vec<Item>, draft: Draft, now: &str) -> bool {
|
|
|
132
355
|
if draft.notes.is_some() {
|
|
133
356
|
item.notes = draft.notes.clone();
|
|
134
357
|
}
|
|
358
|
+
if draft.fields.is_some() {
|
|
359
|
+
item.fields = draft.fields.clone();
|
|
360
|
+
}
|
|
135
361
|
if draft.source.is_some() {
|
|
136
362
|
item.source = draft.source.clone();
|
|
137
363
|
}
|
|
138
364
|
if keep_old_name {
|
|
139
365
|
item.name = before;
|
|
140
366
|
}
|
|
367
|
+
item.sync_login_mirrors();
|
|
141
368
|
item.updated_at = now.to_string();
|
|
142
369
|
return false;
|
|
143
370
|
}
|
|
144
371
|
|
|
145
|
-
|
|
372
|
+
let mut item = Item {
|
|
146
373
|
id: draft.id.unwrap_or_else(random_id),
|
|
147
374
|
name: draft.name,
|
|
375
|
+
r#type: draft.r#type,
|
|
148
376
|
username: draft.username,
|
|
149
377
|
password: draft.password,
|
|
150
378
|
uris: draft.uris,
|
|
379
|
+
data: draft.data,
|
|
151
380
|
notes: draft.notes,
|
|
381
|
+
fields: draft.fields,
|
|
152
382
|
source: draft.source,
|
|
153
383
|
created_at: now.to_string(),
|
|
154
384
|
updated_at: now.to_string(),
|
|
155
|
-
}
|
|
385
|
+
};
|
|
386
|
+
item.sync_login_mirrors();
|
|
387
|
+
items.push(item);
|
|
156
388
|
true
|
|
157
389
|
}
|
|
158
390
|
|