@xiaolikt/ai-vault 0.10.0 → 0.12.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 +45 -7
- package/README.zh.md +34 -5
- package/crates/ai-vault/Cargo.toml +1 -1
- package/crates/ai-vault/src/cli.rs +441 -119
- package/crates/ai-vault/src/config.rs +41 -12
- package/crates/ai-vault/src/crypto.rs +69 -18
- package/crates/ai-vault/src/import.rs +85 -48
- package/crates/ai-vault/src/sealed.rs +1 -9
- package/crates/ai-vault/src/session.rs +79 -22
- package/crates/ai-vault/src/store.rs +237 -5
- package/package.json +4 -4
- package/packages/pi-ai-vault/README.md +1 -1
- package/packages/pi-ai-vault/README.zh.md +1 -1
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +42 -26
- package/packages/pi-ai-vault/src/cli.ts +9 -3
- package/packages/pi-ai-vault/src/import-map.ts +166 -58
- package/packages/pi-ai-vault/src/index.ts +172 -48
- package/packages/pi-ai-vault/src/settings.ts +37 -7
- package/packages/pi-ai-vault/src/types.ts +52 -0
- package/test/cli.sh +112 -24
- package/tests/bitwarden-tools.test.mjs +2 -2
- package/tests/ente.test.mjs +25 -6
- package/tests/helpers.mjs +36 -0
- package/tests/import-map.test.mjs +75 -38
- package/tests/mocks/bin/bw +5 -1
- package/tests/vault-cli.test.mjs +77 -19
|
@@ -78,6 +78,15 @@ pub struct UnlockPolicy {
|
|
|
78
78
|
/// `Time` mode only: hours between password prompts.
|
|
79
79
|
#[serde(default = "default_hours")]
|
|
80
80
|
pub hours: i64,
|
|
81
|
+
/// Whether each read of an entry opens a confirm window while the session
|
|
82
|
+
/// is unlocked. On by default. Off means "the master password I just typed
|
|
83
|
+
/// is enough" — reads are still audited, entry by entry.
|
|
84
|
+
#[serde(default = "default_confirm")]
|
|
85
|
+
pub confirm: bool,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
fn default_confirm() -> bool {
|
|
89
|
+
true
|
|
81
90
|
}
|
|
82
91
|
|
|
83
92
|
fn default_hours() -> i64 {
|
|
@@ -86,7 +95,7 @@ fn default_hours() -> i64 {
|
|
|
86
95
|
|
|
87
96
|
impl Default for UnlockPolicy {
|
|
88
97
|
fn default() -> Self {
|
|
89
|
-
UnlockPolicy { mode: UnlockMode::Session, hours: default_hours() }
|
|
98
|
+
UnlockPolicy { mode: UnlockMode::Session, hours: default_hours(), confirm: default_confirm() }
|
|
90
99
|
}
|
|
91
100
|
}
|
|
92
101
|
|
|
@@ -142,18 +151,37 @@ pub struct Config {
|
|
|
142
151
|
pub ente: StorePolicy,
|
|
143
152
|
}
|
|
144
153
|
|
|
145
|
-
///
|
|
146
|
-
///
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
154
|
+
/// The settings are inside the store's ciphertext (see `crypto::Payload`), so
|
|
155
|
+
/// they can only be read or changed with the store's key: a password, or a
|
|
156
|
+
/// session that was opened with one. There is no file to edit.
|
|
157
|
+
//
|
|
158
|
+
// Callers hold either a `Session` (its key opens the store) or a freshly
|
|
159
|
+
// derived key. Both go through `read_with` / `write_with`.
|
|
160
|
+
pub fn write_with(
|
|
161
|
+
store: &crate::crypto::StoreFile,
|
|
162
|
+
key: &[u8; 32],
|
|
163
|
+
config: &Config,
|
|
164
|
+
) -> Result<crate::crypto::StoreFile, String> {
|
|
165
|
+
let payload = crypto::open_with_key(store, key).map_err(|e| e.to_string())?;
|
|
166
|
+
let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| "vault salt is corrupt".to_string())?;
|
|
167
|
+
crypto::seal(&salt, store.kdf(), key, &payload.items, config)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// A legacy plaintext config.json from before the settings moved inside the
|
|
171
|
+
/// store. Returned once so the next unlock can carry it in; then the file
|
|
172
|
+
/// is removed. Only the *defaults-safe* keys migrate; the two that lower
|
|
173
|
+
/// protection (`vault.unlock = never`, `vault.confirm = false`) do not, so
|
|
174
|
+
/// an edit made while the file was still plain text grants nothing.
|
|
175
|
+
pub fn take_legacy(paths: &Paths) -> Option<Config> {
|
|
176
|
+
let text = fs::read_to_string(paths.config()).ok()?;
|
|
177
|
+
let _ = fs::remove_file(paths.config());
|
|
178
|
+
let Ok(parsed) = serde_json::from_str::<Config>(&text) else { return None };
|
|
179
|
+
let mut config = parsed;
|
|
180
|
+
if config.unlock.mode == UnlockMode::Never {
|
|
181
|
+
config.unlock.mode = UnlockMode::Session;
|
|
151
182
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
pub fn save(paths: &Paths, config: &Config) -> Result<(), String> {
|
|
155
|
-
let bytes = serde_json::to_vec_pretty(config).map_err(|e| format!("cannot serialize config: {e}"))?;
|
|
156
|
-
crypto::write_atomic(&paths.config(), &bytes)
|
|
183
|
+
config.unlock.confirm = true;
|
|
184
|
+
Some(config)
|
|
157
185
|
}
|
|
158
186
|
|
|
159
187
|
#[cfg(test)]
|
|
@@ -183,6 +211,7 @@ mod tests {
|
|
|
183
211
|
// A config written by the previous version had only `unlock`.
|
|
184
212
|
let parsed: Config = serde_json::from_str(r#"{"unlock":{"mode":"time","hours":4}}"#).unwrap();
|
|
185
213
|
assert_eq!(parsed.unlock.mode, UnlockMode::Time);
|
|
214
|
+
assert_eq!(parsed.unlock.confirm, true, "a config from before the switch keeps confirming");
|
|
186
215
|
assert_eq!(parsed.bitwarden.import, ImportPolicy::Ask);
|
|
187
216
|
assert_eq!(parsed.bitwarden.store.hours, 8);
|
|
188
217
|
}
|
|
@@ -115,8 +115,20 @@ pub fn store_id(store: &StoreFile) -> String {
|
|
|
115
115
|
digest.iter().take(12).map(|b| format!("{b:02x}")).collect()
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
-
|
|
119
|
-
|
|
118
|
+
/// What the ciphertext holds: the entries and the settings together, so the
|
|
119
|
+
/// settings are protected by the same key as the passwords and cannot be
|
|
120
|
+
/// edited on disk. `v: 1` files (before settings moved in) hold a bare array
|
|
121
|
+
/// of items and are read as "all defaults".
|
|
122
|
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
123
|
+
pub struct Payload {
|
|
124
|
+
pub items: Vec<Item>,
|
|
125
|
+
#[serde(default)]
|
|
126
|
+
pub config: crate::config::Config,
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
pub fn seal(salt: &[u8], kdf: Kdf, key: &[u8; 32], items: &[Item], config: &crate::config::Config) -> Result<StoreFile, String> {
|
|
130
|
+
let plaintext = serde_json::to_vec(&Payload { items: items.to_vec(), config: *config })
|
|
131
|
+
.map_err(|e| format!("cannot serialize vault: {e}"))?;
|
|
120
132
|
let iv = random_bytes::<12>();
|
|
121
133
|
let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| format!("bad key: {e}"))?;
|
|
122
134
|
let body = cipher
|
|
@@ -133,7 +145,7 @@ pub fn seal(salt: &[u8], kdf: Kdf, key: &[u8; 32], items: &[Item]) -> Result<Sto
|
|
|
133
145
|
})
|
|
134
146
|
}
|
|
135
147
|
|
|
136
|
-
pub fn open_with_key(store: &StoreFile, key: &[u8; 32]) -> Result<
|
|
148
|
+
pub fn open_with_key(store: &StoreFile, key: &[u8; 32]) -> Result<Payload, OpenError> {
|
|
137
149
|
if store.v != 1 {
|
|
138
150
|
return Err(OpenError::Broken("unsupported vault format".into()));
|
|
139
151
|
}
|
|
@@ -146,16 +158,21 @@ pub fn open_with_key(store: &StoreFile, key: &[u8; 32]) -> Result<Vec<Item>, Ope
|
|
|
146
158
|
let (iv, body) = blob.split_at(12);
|
|
147
159
|
let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|_| OpenError::Broken("bad key".into()))?;
|
|
148
160
|
let plaintext = cipher
|
|
149
|
-
.decrypt(Nonce::from_slice(iv), body)
|
|
150
|
-
|
|
151
|
-
|
|
161
|
+
.decrypt(Nonce::from_slice(iv), body).map_err(|_| OpenError::WrongPassword)?;
|
|
162
|
+
// A bare array is a v1 store written before settings lived inside; the
|
|
163
|
+
// defaults apply to it. A wrong password cannot reach here (the tag
|
|
164
|
+
// fails first), so a parse error really is a format problem.
|
|
165
|
+
if let Ok(items) = serde_json::from_slice::<Vec<Item>>(&plaintext) {
|
|
166
|
+
return Ok(Payload { items, config: crate::config::Config::default() });
|
|
167
|
+
}
|
|
168
|
+
serde_json::from_slice(&plaintext).map_err(|_| OpenError::Broken("vault contents are not a store this version understands".into()))
|
|
152
169
|
}
|
|
153
170
|
|
|
154
|
-
pub fn open_with_passphrase(store: &StoreFile, passphrase: &str) -> Result<(
|
|
171
|
+
pub fn open_with_passphrase(store: &StoreFile, passphrase: &str) -> Result<(Payload, Key), OpenError> {
|
|
155
172
|
let salt = hex_to_bytes(&store.salt).ok_or_else(|| OpenError::Broken("vault salt is not hex".into()))?;
|
|
156
173
|
let key = derive_key(passphrase, &salt, store.kdf())?;
|
|
157
|
-
let
|
|
158
|
-
Ok((
|
|
174
|
+
let payload = open_with_key(store, &key)?;
|
|
175
|
+
Ok((payload, key))
|
|
159
176
|
}
|
|
160
177
|
|
|
161
178
|
pub fn hex_to_bytes(text: &str) -> Option<Vec<u8>> {
|
|
@@ -238,12 +255,12 @@ mod tests {
|
|
|
238
255
|
let salt = random_bytes::<16>();
|
|
239
256
|
let kdf = fast();
|
|
240
257
|
let key = derive_key("correct horse", &salt, kdf).unwrap();
|
|
241
|
-
let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
|
|
258
|
+
let sealed = seal(&salt, kdf, &key, &sample(), &Default::default()).unwrap();
|
|
242
259
|
let opened = open_with_key(&sealed, &key).unwrap();
|
|
243
|
-
assert_eq!(opened.len(), 1);
|
|
244
|
-
assert_eq!(opened[0].password, "hunter2");
|
|
260
|
+
assert_eq!(opened.items.len(), 1);
|
|
261
|
+
assert_eq!(opened.items[0].password, "hunter2");
|
|
245
262
|
let (again, _) = open_with_passphrase(&sealed, "correct horse").unwrap();
|
|
246
|
-
assert_eq!(again[0].username.as_deref(), Some("octo"));
|
|
263
|
+
assert_eq!(again.items[0].username.as_deref(), Some("octo"));
|
|
247
264
|
}
|
|
248
265
|
|
|
249
266
|
#[test]
|
|
@@ -251,7 +268,7 @@ mod tests {
|
|
|
251
268
|
let salt = random_bytes::<16>();
|
|
252
269
|
let kdf = fast();
|
|
253
270
|
let key = derive_key("right", &salt, kdf).unwrap();
|
|
254
|
-
let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
|
|
271
|
+
let sealed = seal(&salt, kdf, &key, &sample(), &Default::default()).unwrap();
|
|
255
272
|
assert!(matches!(open_with_passphrase(&sealed, "wrong"), Err(OpenError::WrongPassword)));
|
|
256
273
|
}
|
|
257
274
|
|
|
@@ -259,11 +276,45 @@ mod tests {
|
|
|
259
276
|
fn each_seal_uses_a_fresh_iv() {
|
|
260
277
|
let salt = random_bytes::<16>();
|
|
261
278
|
let key = derive_key("pw", &salt, fast()).unwrap();
|
|
262
|
-
let a = seal(&salt, fast(), &key, &sample()).unwrap();
|
|
263
|
-
let b = seal(&salt, fast(), &key, &sample()).unwrap();
|
|
279
|
+
let a = seal(&salt, fast(), &key, &sample(), &Default::default()).unwrap();
|
|
280
|
+
let b = seal(&salt, fast(), &key, &sample(), &Default::default()).unwrap();
|
|
264
281
|
assert_ne!(a.ct, b.ct);
|
|
265
282
|
}
|
|
266
283
|
|
|
284
|
+
#[test]
|
|
285
|
+
fn settings_live_inside_the_ciphertext() {
|
|
286
|
+
let salt = random_bytes::<16>();
|
|
287
|
+
let kdf = fast();
|
|
288
|
+
let key = derive_key("pw", &salt, kdf).unwrap();
|
|
289
|
+
let mut config = crate::config::Config::default();
|
|
290
|
+
config.unlock.confirm = false;
|
|
291
|
+
let sealed = seal(&salt, kdf, &key, &sample(), &config).unwrap();
|
|
292
|
+
let text = serde_json::to_string(&sealed).unwrap();
|
|
293
|
+
assert!(!text.contains("confirm"), "the settings must not be readable on disk");
|
|
294
|
+
let opened = open_with_key(&sealed, &key).unwrap();
|
|
295
|
+
assert!(!opened.config.unlock.confirm);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
#[test]
|
|
299
|
+
fn a_v1_bare_array_store_still_opens() {
|
|
300
|
+
use chacha20poly1305::aead::{Aead, KeyInit};
|
|
301
|
+
use chacha20poly1305::{ChaCha20Poly1305, Nonce};
|
|
302
|
+
use base64::Engine as _;
|
|
303
|
+
let salt = random_bytes::<16>();
|
|
304
|
+
let kdf = fast();
|
|
305
|
+
let key = derive_key("pw", &salt, kdf).unwrap();
|
|
306
|
+
let cipher = ChaCha20Poly1305::new_from_slice(key.as_ref()).unwrap();
|
|
307
|
+
let iv = random_bytes::<12>();
|
|
308
|
+
let plain = serde_json::to_vec(&sample()).unwrap();
|
|
309
|
+
let body = cipher.encrypt(Nonce::from_slice(&iv), plain.as_slice()).unwrap();
|
|
310
|
+
let mut blob = iv.to_vec();
|
|
311
|
+
blob.extend_from_slice(&body);
|
|
312
|
+
let v1 = StoreFile { v: 1, salt: salt.iter().map(|b| format!("{b:02x}")).collect(), kdf: Some(kdf), ct: base64::engine::general_purpose::STANDARD.encode(blob) };
|
|
313
|
+
let (payload, _) = open_with_passphrase(&v1, "pw").unwrap();
|
|
314
|
+
assert_eq!(payload.items[0].name, "GitHub");
|
|
315
|
+
assert!(payload.config.unlock.confirm, "a store from before the switch keeps the safe default");
|
|
316
|
+
}
|
|
317
|
+
|
|
267
318
|
#[test]
|
|
268
319
|
fn refuses_a_downgraded_kdf() {
|
|
269
320
|
let weak = Kdf { n: 1 << 12, r: 8, p: 1 };
|
|
@@ -276,9 +327,9 @@ mod tests {
|
|
|
276
327
|
// Written by the TS release, with the default KDF.
|
|
277
328
|
let salt = "00112233445566778899aabbccddeeff";
|
|
278
329
|
let key = derive_key("pw", &hex_to_bytes(salt).unwrap(), fast()).unwrap();
|
|
279
|
-
let sealed = seal(&hex_to_bytes(salt).unwrap(), fast(), &key, &sample()).unwrap();
|
|
330
|
+
let sealed = seal(&hex_to_bytes(salt).unwrap(), fast(), &key, &sample(), &Default::default()).unwrap();
|
|
280
331
|
let json = serde_json::json!({ "v": 1, "salt": salt, "kdf": { "N": 32768, "r": 8, "p": 1 }, "ct": sealed.ct });
|
|
281
332
|
let store: StoreFile = serde_json::from_value(json).unwrap();
|
|
282
|
-
assert_eq!(open_with_passphrase(&store, "pw").unwrap().0[0].name, "GitHub");
|
|
333
|
+
assert_eq!(open_with_passphrase(&store, "pw").unwrap().0.items[0].name, "GitHub");
|
|
283
334
|
}
|
|
284
335
|
}
|
|
@@ -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]
|
|
@@ -33,12 +33,6 @@ impl Kind {
|
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
fn policy(self, config: &config::Config) -> config::StorePolicy {
|
|
37
|
-
match self {
|
|
38
|
-
Kind::Bitwarden => config.bitwarden.store,
|
|
39
|
-
Kind::Ente => config.ente,
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
36
|
}
|
|
43
37
|
|
|
44
38
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
@@ -124,9 +118,7 @@ impl Stored {
|
|
|
124
118
|
|
|
125
119
|
/// Store a key, honouring the current `bitwarden.unlock` policy. `session`
|
|
126
120
|
/// means "do not persist": the caller keeps it in memory instead.
|
|
127
|
-
pub fn save(paths: &Paths, kind: Kind, secret: &str) -> Result<Option<i64>, String> {
|
|
128
|
-
let config = config::load(paths);
|
|
129
|
-
let policy = kind.policy(&config);
|
|
121
|
+
pub fn save(paths: &Paths, kind: Kind, secret: &str, policy: config::StorePolicy) -> Result<Option<i64>, String> {
|
|
130
122
|
if policy.unlock == UnlockMode::Session {
|
|
131
123
|
clear(paths, kind);
|
|
132
124
|
return Err(format!(
|
|
@@ -54,9 +54,42 @@ pub struct Session {
|
|
|
54
54
|
/// by definition not protected from this user.
|
|
55
55
|
#[serde(default, skip_serializing_if = "Option::is_none", rename = "mac")]
|
|
56
56
|
pub mac: Option<String>,
|
|
57
|
+
/// Which key signed `mac`: "host" (the extension's in-memory secret) or
|
|
58
|
+
/// "wrap" (the store's key, for a human at a terminal). Verification uses
|
|
59
|
+
/// the key actually named here, never whichever one happens to be in the
|
|
60
|
+
/// environment — so a token created one way is not voided by a call made
|
|
61
|
+
/// the other way.
|
|
62
|
+
#[serde(default, skip_serializing_if = "Option::is_none", rename = "signedBy")]
|
|
63
|
+
pub signed_by: Option<String>,
|
|
57
64
|
}
|
|
58
65
|
|
|
59
66
|
|
|
67
|
+
/// Who signs a session file: the host process's in-memory secret, or the
|
|
68
|
+
/// store's wrap key when a human runs `ai-vault` by hand.
|
|
69
|
+
pub enum Signer {
|
|
70
|
+
Host(String),
|
|
71
|
+
Wrap(String),
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
impl Signer {
|
|
75
|
+
fn label(&self) -> &'static str {
|
|
76
|
+
match self {
|
|
77
|
+
Signer::Host(_) => "host",
|
|
78
|
+
Signer::Wrap(_) => "wrap",
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
fn hmac(&self, body: &[u8]) -> String {
|
|
83
|
+
use hmac::{Hmac, Mac};
|
|
84
|
+
let key = match self {
|
|
85
|
+
Signer::Host(k) | Signer::Wrap(k) => k.as_str(),
|
|
86
|
+
};
|
|
87
|
+
let mut hasher = <Hmac<sha2::Sha256> as Mac>::new_from_slice(key.as_bytes()).expect("HMAC takes any key length");
|
|
88
|
+
hasher.update(body);
|
|
89
|
+
hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
60
93
|
fn mac_body(session: &Session) -> Vec<u8> {
|
|
61
94
|
// Same struct, `mac` blanked, canonical key order: serde_json::Value sorts
|
|
62
95
|
// object keys, so the encoding is stable across runs.
|
|
@@ -83,35 +116,48 @@ impl Session {
|
|
|
83
116
|
key: B64.encode(key),
|
|
84
117
|
grants: BTreeMap::new(),
|
|
85
118
|
mac: None,
|
|
119
|
+
signed_by: None,
|
|
86
120
|
}
|
|
87
121
|
}
|
|
88
122
|
|
|
89
|
-
/// (Re)sign this session
|
|
90
|
-
pub fn sign(&mut self,
|
|
91
|
-
self.
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
.expect("HMAC takes any key length");
|
|
95
|
-
hasher.update(&mac_body(self));
|
|
96
|
-
hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()
|
|
97
|
-
});
|
|
123
|
+
/// (Re)sign this session and record who signed it. Called before every save.
|
|
124
|
+
pub fn sign(&mut self, signer: &Signer) {
|
|
125
|
+
self.signed_by = Some(signer.label().to_string());
|
|
126
|
+
let body = mac_body(self);
|
|
127
|
+
self.mac = Some(signer.hmac(&body));
|
|
98
128
|
}
|
|
99
129
|
|
|
100
|
-
/// True when the file was written by
|
|
101
|
-
///
|
|
102
|
-
pub fn verifies(&self, host_secret: Option<&str>) -> bool {
|
|
103
|
-
let
|
|
104
|
-
// The only legitimate unsigned session is the machine-wide one
|
|
105
|
-
|
|
130
|
+
/// True when the file was written by whoever it says signed it, checked
|
|
131
|
+
/// with *that* key — never whichever one happens to be in the environment.
|
|
132
|
+
pub fn verifies(&self, host_secret: Option<&str>, wrap_key: Option<&str>) -> bool {
|
|
133
|
+
let Some(mac) = self.mac.as_deref() else {
|
|
134
|
+
// The only legitimate unsigned session is the machine-wide one,
|
|
135
|
+
// which is protected by the directory instead.
|
|
136
|
+
return host_secret.is_none() && wrap_key.is_none();
|
|
137
|
+
};
|
|
138
|
+
let key: &str = match self.signed_by.as_deref() {
|
|
139
|
+
Some("host") => match host_secret {
|
|
140
|
+
Some(k) => k,
|
|
141
|
+
None => return false,
|
|
142
|
+
},
|
|
143
|
+
Some("wrap") => match wrap_key {
|
|
144
|
+
Some(k) => k,
|
|
145
|
+
None => return false,
|
|
146
|
+
},
|
|
147
|
+
// A file from before `signedBy`: accept whichever key fits.
|
|
148
|
+
_ => match host_secret.or(wrap_key) {
|
|
149
|
+
Some(k) => k,
|
|
150
|
+
None => return false,
|
|
151
|
+
},
|
|
106
152
|
};
|
|
107
153
|
use hmac::{Hmac, Mac};
|
|
108
|
-
let Ok(mut hasher) = <Hmac<sha2::Sha256> as Mac>::new_from_slice(
|
|
154
|
+
let Ok(mut hasher) = <Hmac<sha2::Sha256> as Mac>::new_from_slice(key.as_bytes()) else {
|
|
109
155
|
return false;
|
|
110
156
|
};
|
|
111
157
|
hasher.update(&mac_body(self));
|
|
112
158
|
let expected: String = hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
|
|
113
|
-
|
|
114
|
-
|
|
159
|
+
expected.len() == mac.len()
|
|
160
|
+
&& expected.bytes().zip(mac.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0
|
|
115
161
|
}
|
|
116
162
|
|
|
117
163
|
pub fn key(&self) -> Option<Zeroizing<[u8; 32]>> {
|
|
@@ -152,9 +198,9 @@ impl Session {
|
|
|
152
198
|
.filter(|until| *until > now)
|
|
153
199
|
}
|
|
154
200
|
|
|
155
|
-
pub fn save(&self, paths: &Paths,
|
|
201
|
+
pub fn save(&self, paths: &Paths, signer: &Signer) -> Result<(), String> {
|
|
156
202
|
let mut signed = self.clone();
|
|
157
|
-
signed.sign(
|
|
203
|
+
signed.sign(signer);
|
|
158
204
|
let dir = paths.sessions();
|
|
159
205
|
fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
|
160
206
|
crate::perms::restrict_dir(&dir);
|
|
@@ -165,7 +211,7 @@ impl Session {
|
|
|
165
211
|
|
|
166
212
|
/// Load a token for the given store. Missing, expired, or stale tokens are
|
|
167
213
|
/// removed and reported as locked so the caller unlocks again.
|
|
168
|
-
pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>) -> Result<Session, String> {
|
|
214
|
+
pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>, wrap_key: Option<&str>) -> Result<Session, String> {
|
|
169
215
|
let path = paths.session_file(token);
|
|
170
216
|
let text = match fs::read_to_string(&path) {
|
|
171
217
|
Ok(text) => text,
|
|
@@ -183,7 +229,18 @@ pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>) -> Result<Ses
|
|
|
183
229
|
}
|
|
184
230
|
// Edited on disk (a grant minted, a requester renamed): treat as a break-in
|
|
185
231
|
// attempt, say so, and drop it.
|
|
186
|
-
|
|
232
|
+
// Only a file this caller holds a key for is judged; one signed under a
|
|
233
|
+
// key the caller does not have is simply not theirs to use (and is left
|
|
234
|
+
// alone for whoever does hold that key).
|
|
235
|
+
let has_key_for_it = match session.signed_by.as_deref() {
|
|
236
|
+
Some("host") => host_secret.is_some(),
|
|
237
|
+
Some("wrap") => wrap_key.is_some(),
|
|
238
|
+
_ => host_secret.is_some() || wrap_key.is_some(),
|
|
239
|
+
};
|
|
240
|
+
if !has_key_for_it {
|
|
241
|
+
return Err("this session belongs to another caller — unlock again".into());
|
|
242
|
+
}
|
|
243
|
+
if !session.verifies(host_secret, wrap_key) {
|
|
187
244
|
let _ = fs::remove_file(&path);
|
|
188
245
|
return Err("session file was modified outside ai-vault — unlock again".into());
|
|
189
246
|
}
|