@xiaolikt/ai-vault 0.0.0-stage → 0.4.1

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.
@@ -0,0 +1,265 @@
1
+ //! Encryption at rest and the on-disk store format.
2
+ //!
3
+ //! store.json:
4
+ //! { "v": 1, "salt": "<hex>", "kdf": { "N", "r", "p" },
5
+ //! "ct": "<base64 iv(12) || ciphertext || tag(16)>" }
6
+ //!
7
+ //! Sealed with ChaCha20-Poly1305 (RFC 8439) after scrypt(passphrase, salt).
8
+ //! Identical to the format the TypeScript release used, so an existing store
9
+ //! opens without a migration step.
10
+
11
+ use std::fs::{self, File, OpenOptions};
12
+ use std::io::Write;
13
+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
14
+ use std::path::Path;
15
+
16
+ use base64::engine::general_purpose::STANDARD as B64;
17
+ use base64::Engine as _;
18
+ use chacha20poly1305::aead::{Aead, KeyInit};
19
+ use chacha20poly1305::{ChaCha20Poly1305, Nonce};
20
+ use serde::{Deserialize, Serialize};
21
+ use sha2::{Digest, Sha256};
22
+ use zeroize::Zeroizing;
23
+
24
+ use crate::store::Item;
25
+
26
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
27
+ pub struct Kdf {
28
+ #[serde(rename = "N")]
29
+ pub n: u32,
30
+ pub r: u32,
31
+ pub p: u32,
32
+ }
33
+
34
+ impl Default for Kdf {
35
+ fn default() -> Self {
36
+ Kdf { n: 1 << 15, r: 8, p: 1 }
37
+ }
38
+ }
39
+
40
+ #[derive(Debug, Clone, Serialize, Deserialize)]
41
+ pub struct StoreFile {
42
+ pub v: u32,
43
+ pub salt: String,
44
+ #[serde(default, skip_serializing_if = "Option::is_none")]
45
+ pub kdf: Option<Kdf>,
46
+ pub ct: String,
47
+ }
48
+
49
+ impl StoreFile {
50
+ pub fn kdf(&self) -> Kdf {
51
+ self.kdf.unwrap_or_default()
52
+ }
53
+ }
54
+
55
+ #[derive(Debug)]
56
+ pub enum OpenError {
57
+ /// Wrong master password (the AEAD tag did not verify).
58
+ WrongPassword,
59
+ /// Right password, but the file is not a store this version understands.
60
+ Broken(String),
61
+ }
62
+
63
+ impl std::fmt::Display for OpenError {
64
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65
+ match self {
66
+ OpenError::WrongPassword => write!(f, "wrong master password"),
67
+ OpenError::Broken(msg) => write!(f, "{msg}"),
68
+ }
69
+ }
70
+ }
71
+
72
+ pub type Key = Zeroizing<[u8; 32]>;
73
+
74
+ pub fn random_bytes<const N: usize>() -> [u8; N] {
75
+ let mut buf = [0u8; N];
76
+ getrandom::getrandom(&mut buf).expect("the OS random generator must work");
77
+ buf
78
+ }
79
+
80
+ /// scrypt(passphrase, salt, N/r/p) -> 32-byte key.
81
+ pub fn derive_key(passphrase: &str, salt: &[u8], kdf: Kdf) -> Result<Key, OpenError> {
82
+ let log_n = u8::try_from(kdf.n.trailing_zeros()).map_err(|_| OpenError::Broken("bad KDF parameters".into()))?;
83
+ if kdf.n == 0 || (1u32 << log_n) != kdf.n {
84
+ return Err(OpenError::Broken("bad KDF parameters".into()));
85
+ }
86
+ let params = scrypt::Params::new(log_n, kdf.r, kdf.p, 32)
87
+ .map_err(|e| OpenError::Broken(format!("bad KDF parameters: {e}")))?;
88
+ let mut key = Zeroizing::new([0u8; 32]);
89
+ scrypt::scrypt(passphrase.as_bytes(), salt, &params, key.as_mut())
90
+ .map_err(|e| OpenError::Broken(format!("key derivation failed: {e}")))?;
91
+ Ok(key)
92
+ }
93
+
94
+ /// Fingerprint of the store's salt: it changes only when the vault is
95
+ /// re-created, so a session token from before that is rejected instead of
96
+ /// decrypting garbage. (It must not cover the ciphertext: every save rewrites
97
+ /// that.)
98
+ pub fn store_id(store: &StoreFile) -> String {
99
+ let mut hasher = Sha256::new();
100
+ hasher.update(store.salt.as_bytes());
101
+ let digest = hasher.finalize();
102
+ digest.iter().take(12).map(|b| format!("{b:02x}")).collect()
103
+ }
104
+
105
+ pub fn seal(salt: &[u8], kdf: Kdf, key: &[u8; 32], items: &[Item]) -> Result<StoreFile, String> {
106
+ let plaintext = serde_json::to_vec(items).map_err(|e| format!("cannot serialize vault: {e}"))?;
107
+ let iv = random_bytes::<12>();
108
+ let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| format!("bad key: {e}"))?;
109
+ let body = cipher
110
+ .encrypt(Nonce::from_slice(&iv), plaintext.as_ref())
111
+ .map_err(|_| "encryption failed".to_string())?;
112
+ let mut blob = Vec::with_capacity(12 + body.len());
113
+ blob.extend_from_slice(&iv);
114
+ blob.extend_from_slice(&body);
115
+ Ok(StoreFile {
116
+ v: 1,
117
+ salt: salt.iter().map(|b| format!("{b:02x}")).collect(),
118
+ kdf: Some(kdf),
119
+ ct: B64.encode(blob),
120
+ })
121
+ }
122
+
123
+ pub fn open_with_key(store: &StoreFile, key: &[u8; 32]) -> Result<Vec<Item>, OpenError> {
124
+ if store.v != 1 {
125
+ return Err(OpenError::Broken("unsupported vault format".into()));
126
+ }
127
+ let blob = B64
128
+ .decode(store.ct.as_bytes())
129
+ .map_err(|_| OpenError::Broken("vault file is not valid base64".into()))?;
130
+ if blob.len() < 12 + 16 {
131
+ return Err(OpenError::Broken("vault file is truncated".into()));
132
+ }
133
+ let (iv, body) = blob.split_at(12);
134
+ let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|_| OpenError::Broken("bad key".into()))?;
135
+ let plaintext = cipher
136
+ .decrypt(Nonce::from_slice(iv), body)
137
+ .map_err(|_| OpenError::WrongPassword)?;
138
+ serde_json::from_slice(&plaintext).map_err(|_| OpenError::Broken("vault contents are not a list of entries".into()))
139
+ }
140
+
141
+ pub fn open_with_passphrase(store: &StoreFile, passphrase: &str) -> Result<(Vec<Item>, Key), OpenError> {
142
+ let salt = hex_to_bytes(&store.salt).ok_or_else(|| OpenError::Broken("vault salt is not hex".into()))?;
143
+ let key = derive_key(passphrase, &salt, store.kdf())?;
144
+ let items = open_with_key(store, &key)?;
145
+ Ok((items, key))
146
+ }
147
+
148
+ pub fn hex_to_bytes(text: &str) -> Option<Vec<u8>> {
149
+ if text.len() % 2 != 0 {
150
+ return None;
151
+ }
152
+ (0..text.len())
153
+ .step_by(2)
154
+ .map(|i| u8::from_str_radix(&text[i..i + 2], 16).ok())
155
+ .collect()
156
+ }
157
+
158
+ pub fn read_store(path: &Path) -> Result<Option<StoreFile>, String> {
159
+ match fs::read_to_string(path) {
160
+ Ok(text) => serde_json::from_str(&text)
161
+ .map(Some)
162
+ .map_err(|e| format!("cannot parse {}: {e}", path.display())),
163
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
164
+ Err(e) => Err(format!("cannot read {}: {e}", path.display())),
165
+ }
166
+ }
167
+
168
+ /// Write through a temp file, fsync it, rename, then fsync the directory.
169
+ /// Mode is 0600 from the moment the temp file exists.
170
+ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
171
+ let dir = path.parent().unwrap_or(Path::new("."));
172
+ fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
173
+ let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
174
+
175
+ let tmp = dir.join(format!(
176
+ ".{}.{}.{}.tmp",
177
+ path.file_name().and_then(|n| n.to_str()).unwrap_or("store.json"),
178
+ std::process::id(),
179
+ B64.encode(random_bytes::<6>()).replace(['/', '+', '='], "")
180
+ ));
181
+ let mut file = OpenOptions::new()
182
+ .write(true)
183
+ .create_new(true)
184
+ .mode(0o600)
185
+ .open(&tmp)
186
+ .map_err(|e| format!("cannot create a temp file next to {}: {e}", path.display()))?;
187
+ let outcome = (|| -> std::io::Result<()> {
188
+ file.write_all(bytes)?;
189
+ file.sync_all()?;
190
+ drop(file);
191
+ fs::rename(&tmp, path)
192
+ })();
193
+ if let Err(e) = outcome {
194
+ let _ = fs::remove_file(&tmp);
195
+ return Err(format!("cannot write {}: {e}", path.display()));
196
+ }
197
+ if let Ok(dir_file) = File::open(dir) {
198
+ let _ = dir_file.sync_all();
199
+ }
200
+ Ok(())
201
+ }
202
+
203
+ #[cfg(test)]
204
+ mod tests {
205
+ use super::*;
206
+ use crate::store::Draft;
207
+
208
+ fn sample() -> Vec<Item> {
209
+ let mut items = Vec::new();
210
+ crate::store::apply(
211
+ &mut items,
212
+ Draft {
213
+ name: "GitHub".into(),
214
+ username: Some("octo".into()),
215
+ password: "hunter2".into(),
216
+ uris: Some(vec!["https://github.com".into()]),
217
+ ..Default::default()
218
+ },
219
+ "2026-01-01T00:00:00.000Z",
220
+ );
221
+ items
222
+ }
223
+
224
+ #[test]
225
+ fn round_trip() {
226
+ let salt = random_bytes::<16>();
227
+ let kdf = Kdf::default();
228
+ let key = derive_key("correct horse", &salt, kdf).unwrap();
229
+ let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
230
+ let opened = open_with_key(&sealed, &key).unwrap();
231
+ assert_eq!(opened.len(), 1);
232
+ assert_eq!(opened[0].password, "hunter2");
233
+ let (again, _) = open_with_passphrase(&sealed, "correct horse").unwrap();
234
+ assert_eq!(again[0].username.as_deref(), Some("octo"));
235
+ }
236
+
237
+ #[test]
238
+ fn wrong_password_is_distinguishable() {
239
+ let salt = random_bytes::<16>();
240
+ let kdf = Kdf::default();
241
+ let key = derive_key("right", &salt, kdf).unwrap();
242
+ let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
243
+ assert!(matches!(open_with_passphrase(&sealed, "wrong"), Err(OpenError::WrongPassword)));
244
+ }
245
+
246
+ #[test]
247
+ fn each_seal_uses_a_fresh_iv() {
248
+ let salt = random_bytes::<16>();
249
+ let key = derive_key("pw", &salt, Kdf::default()).unwrap();
250
+ let a = seal(&salt, Kdf::default(), &key, &sample()).unwrap();
251
+ let b = seal(&salt, Kdf::default(), &key, &sample()).unwrap();
252
+ assert_ne!(a.ct, b.ct);
253
+ }
254
+
255
+ #[test]
256
+ fn parses_the_typescript_format() {
257
+ // Written by the TS release, with the default KDF.
258
+ let salt = "00112233445566778899aabbccddeeff";
259
+ let key = derive_key("pw", &hex_to_bytes(salt).unwrap(), Kdf::default()).unwrap();
260
+ let sealed = seal(&hex_to_bytes(salt).unwrap(), Kdf::default(), &key, &sample()).unwrap();
261
+ let json = serde_json::json!({ "v": 1, "salt": salt, "kdf": { "N": 32768, "r": 8, "p": 1 }, "ct": sealed.ct });
262
+ let store: StoreFile = serde_json::from_value(json).unwrap();
263
+ assert_eq!(open_with_passphrase(&store, "pw").unwrap().0[0].name, "GitHub");
264
+ }
265
+ }
@@ -0,0 +1,222 @@
1
+ //! Desktop dialogs, the same zenity windows the TypeScript release opened.
2
+ //!
3
+ //! When a display exists but zenity cannot run, the caller gets `NoUi` and
4
+ //! falls back to its host UI (pi/omp prompt). Cancel and our own timeout end
5
+ //! the prompt here: they never turn into a second prompt.
6
+
7
+ use std::env;
8
+ use std::path::Path;
9
+ use std::process::{Command, Stdio};
10
+
11
+ const DIALOG_SECONDS: u32 = 600;
12
+
13
+ pub enum Answer<T> {
14
+ /// The user answered.
15
+ Value(T),
16
+ /// The user cancelled, or the window timed out.
17
+ Cancelled,
18
+ /// No window could be opened at all; ask the host UI instead.
19
+ NoUi,
20
+ }
21
+
22
+ pub fn has_display() -> bool {
23
+ ["DISPLAY", "WAYLAND_DISPLAY"]
24
+ .iter()
25
+ .any(|name| env::var_os(name).is_some_and(|v| !v.is_empty()))
26
+ }
27
+
28
+ struct Zenity {
29
+ /// False when the process could not be started at all (zenity missing).
30
+ spawned: bool,
31
+ code: i32,
32
+ stdout: String,
33
+ stderr: String,
34
+ }
35
+
36
+ fn zenity(args: &[String]) -> Zenity {
37
+ match Command::new("zenity")
38
+ .args(args)
39
+ .stdin(Stdio::null())
40
+ .stdout(Stdio::piped())
41
+ .stderr(Stdio::piped())
42
+ .output()
43
+ {
44
+ Ok(out) => Zenity {
45
+ spawned: true,
46
+ code: out.status.code().unwrap_or(-1),
47
+ stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
48
+ stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
49
+ },
50
+ Err(_) => Zenity { spawned: false, code: 127, stdout: String::new(), stderr: String::new() },
51
+ }
52
+ }
53
+
54
+ fn arg(text: impl Into<String>) -> String {
55
+ text.into()
56
+ }
57
+
58
+ fn timeout_arg() -> String {
59
+ format!("--timeout={DIALOG_SECONDS}")
60
+ }
61
+
62
+ fn trim_newline(text: &str) -> String {
63
+ text.trim_end_matches(['\r', '\n']).to_string()
64
+ }
65
+
66
+ /// True when the configured display looks usable. Only consulted when zenity
67
+ /// exits 1 with no output at all: a cancel on a live display, or a silent
68
+ /// start failure on a dead one.
69
+ fn display_reachable() -> bool {
70
+ if let Some(wl) = env::var_os("WAYLAND_DISPLAY").filter(|v| !v.is_empty()) {
71
+ let runtime = match env::var_os("XDG_RUNTIME_DIR") {
72
+ Some(dir) if !dir.is_empty() => dir,
73
+ _ => return false,
74
+ };
75
+ return Path::new(&runtime).join(&wl).exists();
76
+ }
77
+ if env::var_os("DISPLAY").is_none_or(|v| v.is_empty()) {
78
+ return false;
79
+ }
80
+ match Command::new("xdpyinfo")
81
+ .stdin(Stdio::null())
82
+ .stdout(Stdio::null())
83
+ .stderr(Stdio::null())
84
+ .status()
85
+ {
86
+ Ok(status) => status.success(),
87
+ // If the probe itself cannot run, do not turn a normal cancel into a
88
+ // second prompt.
89
+ Err(_) => true,
90
+ }
91
+ }
92
+
93
+ /// True when no dialog ran. Exit 1 is ambiguous on some zenity builds (cancel
94
+ /// and a failed start both use it), so stderr decides: GTK's own diagnostics
95
+ /// carry a `(zenity:PID): Gtk-WARNING` prefix; any other line, or a display
96
+ /// failure, means the window never opened.
97
+ fn failed_to_open(z: &Zenity) -> bool {
98
+ if !z.spawned {
99
+ return true;
100
+ }
101
+ // 0 = answered, 5 = --timeout elapsed.
102
+ if z.code == 0 || z.code == 5 {
103
+ return false;
104
+ }
105
+ if z.code == 1 && z.stdout.is_empty() && z.stderr.is_empty() {
106
+ return !display_reachable();
107
+ }
108
+ let lower = z.stderr.to_lowercase();
109
+ if lower.contains("cannot open display") || lower.contains("unable to open") || lower.contains("unable to init")
110
+ || lower.contains("failed to open") || lower.contains("failed to init")
111
+ {
112
+ return true;
113
+ }
114
+ z.stderr
115
+ .lines()
116
+ .map(str::trim)
117
+ .filter(|line| !line.is_empty())
118
+ .any(|line| !is_gtk_diagnostic(line))
119
+ }
120
+
121
+ fn is_gtk_diagnostic(line: &str) -> bool {
122
+ // (zenity:1234): Gtk-WARNING **: ...
123
+ let line = line.trim_start_matches('*');
124
+ let Some(rest) = line.strip_prefix('(') else { return false };
125
+ let Some((program, rest)) = rest.split_once(')') else { return false };
126
+ if !program.contains(':') {
127
+ return false;
128
+ }
129
+ let rest = rest.trim_start_matches(':').trim_start();
130
+ rest.starts_with("Gtk-") || rest.starts_with("Gdk-") || rest.starts_with("GLib-")
131
+ }
132
+
133
+ /// Secret entry. Empty and cancel are both "no value".
134
+ pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
135
+ if !has_display() {
136
+ return Answer::NoUi;
137
+ }
138
+ let z = zenity(&[
139
+ arg("--password"),
140
+ arg(format!("--title={title} — {label}")),
141
+ arg("--width=420"),
142
+ timeout_arg(),
143
+ ]);
144
+ if failed_to_open(&z) {
145
+ return Answer::NoUi;
146
+ }
147
+ let value = trim_newline(&z.stdout);
148
+ if z.code == 0 && !value.is_empty() {
149
+ Answer::Value(value)
150
+ } else {
151
+ Answer::Cancelled
152
+ }
153
+ }
154
+
155
+ /// Plain text entry. Cancel is `Cancelled`; confirming an empty field is `""`.
156
+ pub fn prompt_text(title: &str, label: &str) -> Answer<String> {
157
+ if !has_display() {
158
+ return Answer::NoUi;
159
+ }
160
+ let z = zenity(&[
161
+ arg("--entry"),
162
+ arg(format!("--title={title}")),
163
+ arg(format!("--text={label}")),
164
+ arg("--width=480"),
165
+ arg("--no-markup"),
166
+ timeout_arg(),
167
+ ]);
168
+ if failed_to_open(&z) {
169
+ return Answer::NoUi;
170
+ }
171
+ if z.code == 0 {
172
+ Answer::Value(trim_newline(&z.stdout))
173
+ } else {
174
+ Answer::Cancelled
175
+ }
176
+ }
177
+
178
+ /// Yes/no window. Deny and timeout are false and do not fall through.
179
+ pub fn confirm(title: &str, message: &str) -> Answer<bool> {
180
+ if !has_display() {
181
+ return Answer::NoUi;
182
+ }
183
+ let z = zenity(&[
184
+ arg("--question"),
185
+ arg(format!("--title={title}")),
186
+ arg("--text"),
187
+ arg(message),
188
+ arg("--no-markup"),
189
+ arg("--width=520"),
190
+ arg("--default-cancel"),
191
+ arg("--ok-label=允许"),
192
+ arg("--cancel-label=拒绝"),
193
+ timeout_arg(),
194
+ ]);
195
+ if failed_to_open(&z) {
196
+ return Answer::NoUi;
197
+ }
198
+ Answer::Value(z.code == 0)
199
+ }
200
+
201
+ #[cfg(test)]
202
+ mod tests {
203
+ use super::*;
204
+
205
+ #[test]
206
+ fn gtk_diagnostics_are_not_failures() {
207
+ assert!(is_gtk_diagnostic("(zenity:1234): Gtk-WARNING **: cannot open display"));
208
+ assert!(!is_gtk_diagnostic("zenity: command not found"));
209
+ assert!(!is_gtk_diagnostic("Aborted (core dumped)"));
210
+ }
211
+
212
+ #[test]
213
+ fn failed_spawn_and_dead_display_are_no_ui() {
214
+ let missing = Zenity { spawned: false, code: 127, stdout: String::new(), stderr: String::new() };
215
+ assert!(failed_to_open(&missing));
216
+ let cancel = Zenity { spawned: true, code: 1, stdout: String::new(), stderr: String::new() };
217
+ // No display in the test environment: the same exit is a start failure.
218
+ assert_eq!(failed_to_open(&cancel), !display_reachable());
219
+ let timeout = Zenity { spawned: true, code: 5, stdout: String::new(), stderr: String::new() };
220
+ assert!(!failed_to_open(&timeout));
221
+ }
222
+ }
@@ -0,0 +1,175 @@
1
+ //! Turning external payloads into entries: Bitwarden JSON exports and the
2
+ //! draft array the pi/omp extension sends after reading `bw`.
3
+
4
+ use serde_json::Value;
5
+
6
+ use crate::store::{Draft, Source};
7
+
8
+ const MAX_NAME: usize = 200;
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
+
22
+ fn sanitized_name(raw: &str) -> String {
23
+ let cleaned = raw.replace(['\r', '\n'], " ");
24
+ let cleaned = cleaned.trim();
25
+ if cleaned.is_empty() {
26
+ return "unnamed".to_string();
27
+ }
28
+ cleaned.chars().take(MAX_NAME).collect()
29
+ }
30
+
31
+ /// Bitwarden export (array or `{ "items": [...] }`) -> drafts. Login items
32
+ /// without a password are skipped; names are sorted, then made unique with
33
+ /// `Name (2)`, `Name (3)`, … Each draft keeps its Bitwarden id so a re-import
34
+ /// updates the same row after a rename.
35
+ pub fn from_bitwarden(raw: &Value) -> Result<Vec<Draft>, String> {
36
+ let items = match raw {
37
+ Value::Array(items) => items,
38
+ Value::Object(rec) => {
39
+ if rec.get("encrypted").and_then(Value::as_bool) == Some(true) {
40
+ return Err("This is an encrypted Bitwarden export. Use `bw export --format json` (unencrypted) or /vault import-bw.".into());
41
+ }
42
+ match rec.get("items") {
43
+ Some(Value::Array(items)) => items,
44
+ _ => return Err("Not a Bitwarden export: expected an array of items or an object with `items`.".into()),
45
+ }
46
+ }
47
+ _ => return Err("Not a Bitwarden export: expected an array of items or an object with `items`.".into()),
48
+ };
49
+
50
+ let mut drafts: Vec<Draft> = Vec::new();
51
+ for item in items {
52
+ let Some(rec) = item.as_object() else { continue };
53
+ let Some(login) = rec.get("login").and_then(Value::as_object) else { continue };
54
+ let password = login.get("password").and_then(Value::as_str).unwrap_or("");
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);
69
+ let source = rec
70
+ .get("id")
71
+ .and_then(Value::as_str)
72
+ .filter(|id| !id.is_empty())
73
+ .map(|id| Source { kind: "bitwarden".into(), id: id.to_string() });
74
+ drafts.push(Draft {
75
+ id: None,
76
+ name: sanitized_name(rec.get("name").and_then(Value::as_str).unwrap_or("")),
77
+ username,
78
+ password: password.to_string(),
79
+ uris: Some(as_uris(login)),
80
+ notes,
81
+ source,
82
+ });
83
+ }
84
+
85
+ drafts.sort_by(|a, b| {
86
+ a.name
87
+ .to_lowercase()
88
+ .cmp(&b.name.to_lowercase())
89
+ .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
+ });
96
+ let mut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
97
+ for item in &mut drafts {
98
+ let count = seen.entry(item.name.to_lowercase()).or_insert(0);
99
+ *count += 1;
100
+ if *count > 1 {
101
+ item.name = format!("{} ({count})", item.name);
102
+ }
103
+ }
104
+ Ok(drafts)
105
+ }
106
+
107
+ pub fn parse_bitwarden_json(text: &str) -> Result<Vec<Draft>, String> {
108
+ let value: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?;
109
+ from_bitwarden(&value)
110
+ }
111
+
112
+ /// The `save` payload: an array of drafts, or `{ "items": [...] }`.
113
+ pub fn parse_drafts(text: &str) -> Result<Vec<Draft>, String> {
114
+ let value: Value = serde_json::from_str(text).map_err(|e| format!("invalid JSON: {e}"))?;
115
+ let items = match value {
116
+ Value::Array(items) => items,
117
+ Value::Object(rec) => match rec.get("items") {
118
+ Some(Value::Array(items)) => items.clone(),
119
+ _ => return Err("expected a JSON array of entries".into()),
120
+ },
121
+ _ => return Err("expected a JSON array of entries".into()),
122
+ };
123
+ let mut drafts = Vec::with_capacity(items.len());
124
+ for item in items {
125
+ let draft: Draft = serde_json::from_value(item).map_err(|e| format!("bad entry: {e}"))?;
126
+ if draft.name.trim().is_empty() {
127
+ return Err("every entry needs a name".into());
128
+ }
129
+ drafts.push(draft);
130
+ }
131
+ Ok(drafts)
132
+ }
133
+
134
+ #[cfg(test)]
135
+ mod tests {
136
+ use super::*;
137
+
138
+ #[test]
139
+ fn skips_logins_without_a_password() {
140
+ let raw = serde_json::json!([
141
+ { "id": "1", "name": "Good", "login": { "username": "u", "password": "p", "uris": [{ "uri": "https://a" }] } },
142
+ { "id": "2", "name": "NoPw", "login": { "username": "u" } },
143
+ { "id": "3", "name": "Note only", "notes": "x" }
144
+ ]);
145
+ let drafts = from_bitwarden(&raw).unwrap();
146
+ assert_eq!(drafts.len(), 1);
147
+ assert_eq!(drafts[0].name, "Good");
148
+ assert_eq!(drafts[0].uris.as_ref().unwrap()[0], "https://a");
149
+ assert_eq!(drafts[0].source.as_ref().unwrap().id, "1");
150
+ }
151
+
152
+ #[test]
153
+ fn renames_duplicates_and_sorts() {
154
+ let raw = serde_json::json!([
155
+ { "name": "b", "login": { "password": "1" } },
156
+ { "name": "b", "login": { "password": "2" } },
157
+ { "name": "a", "login": { "password": "3" } }
158
+ ]);
159
+ let names: Vec<_> = from_bitwarden(&raw).unwrap().into_iter().map(|d| d.name).collect();
160
+ assert_eq!(names, vec!["a", "b", "b (2)"]);
161
+ }
162
+
163
+ #[test]
164
+ fn rejects_encrypted_exports() {
165
+ let raw = serde_json::json!({ "encrypted": true, "data": "..." });
166
+ assert!(from_bitwarden(&raw).unwrap_err().contains("encrypted"));
167
+ }
168
+
169
+ #[test]
170
+ fn parses_draft_payloads() {
171
+ let drafts = parse_drafts(r#"[{"name":"x","username":"u","password":"p","uris":["https://x"],"source":{"kind":"bitwarden","id":"9"}}]"#).unwrap();
172
+ assert_eq!(drafts.len(), 1);
173
+ assert_eq!(drafts[0].source.as_ref().unwrap().id, "9");
174
+ }
175
+ }
@@ -0,0 +1,21 @@
1
+ //! ai-vault — one machine-wide encrypted secret store, shared by every agent.
2
+ //!
3
+ //! The store lives at `~/.ai-vault/store.json` (override with `AI_VAULT_DIR`),
4
+ //! encrypted with ChaCha20-Poly1305, keyed by scrypt from the master password.
5
+ //! An agent (pi, omp, anything else) never holds the master password: it asks
6
+ //! this binary to unlock, gets a short-lived session token, and passes that
7
+ //! token back on every later call.
8
+
9
+ mod audit;
10
+ mod cli;
11
+ mod crypto;
12
+ mod dialog;
13
+ mod import;
14
+ mod paths;
15
+ mod session;
16
+ mod store;
17
+
18
+ fn main() {
19
+ let code = cli::run();
20
+ std::process::exit(code);
21
+ }