@xiaolikt/ai-vault 0.11.0 → 0.12.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.
@@ -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
- pub fn seal(salt: &[u8], kdf: Kdf, key: &[u8; 32], items: &[Item]) -> Result<StoreFile, String> {
119
- let plaintext = serde_json::to_vec(items).map_err(|e| format!("cannot serialize vault: {e}"))?;
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<Vec<Item>, OpenError> {
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
- .map_err(|_| OpenError::WrongPassword)?;
151
- serde_json::from_slice(&plaintext).map_err(|_| OpenError::Broken("vault contents are not a list of entries".into()))
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<(Vec<Item>, Key), OpenError> {
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 items = open_with_key(store, &key)?;
158
- Ok((items, key))
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
  }
@@ -6,7 +6,8 @@
6
6
  //!
7
7
  //! When no window can open at all, the caller gets `NoUi` and the host UI
8
8
  //! (pi/omp prompt) takes over. Cancel and our own timeout end the prompt here:
9
- //! they never turn into a second prompt.
9
+ //! they never turn into a second prompt. Every platform answers the value as
10
+ //! UTF-8, whatever the terminal's code page is.
10
11
 
11
12
  #[cfg(not(any(target_os = "macos", target_os = "windows")))]
12
13
  use std::env;
@@ -33,8 +34,17 @@ pub fn has_display() -> bool {
33
34
  .iter()
34
35
  .any(|name| env::var_os(name).is_some_and(|v| !v.is_empty()));
35
36
  }
36
- // macOS and Windows always have a window server for an interactive user.
37
- #[cfg(not(target_os = "linux"))]
37
+ // macOS always has a window server for an interactive user.
38
+ #[cfg(target_os = "macos")]
39
+ {
40
+ true
41
+ }
42
+ // Only the interactive session on Windows has a desktop anyone can see.
43
+ #[cfg(target_os = "windows")]
44
+ {
45
+ win::has_display()
46
+ }
47
+ #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
38
48
  {
39
49
  true
40
50
  }
@@ -163,39 +173,89 @@ mod mac {
163
173
  #[cfg(target_os = "windows")]
164
174
  mod win {
165
175
  use super::{Answer, DIALOG_SECONDS};
176
+ use std::io::Read;
177
+ use std::path::PathBuf;
166
178
  use std::process::{Command, Stdio};
179
+ use std::thread::JoinHandle;
180
+ use std::time::{Duration, Instant};
167
181
 
168
182
  // WinForms from PowerShell: no extra dependency, and PasswordChar can hide
169
183
  // the input. Exit 0 = OK (value on stdout), 1 = cancel, 2 = no window.
184
+ //
185
+ // Two things matter on a real Windows desktop:
186
+ // * `[Console]::Out.Write` encodes with the console's code page (936 on a
187
+ // Chinese Windows), so a password typed in Chinese arrived as mojibake
188
+ // and keyed a store no other machine could open. The value leaves as
189
+ // UTF-8 bytes through the raw stream instead.
190
+ // * Any error (a policy that forbids Add-Type, WinForms that will not
191
+ // load) used to make PowerShell exit 1, which reads as "the user
192
+ // cancelled": the host was told not to retry. The scripts trap into
193
+ // exit 2, and an exit 1 that printed an error counts the same.
170
194
  const PREAMBLE: &str = r#"
171
- Add-Type -AssemblyName System.Windows.Forms, System.Drawing
172
- $f = New-Object System.Windows.Forms.Form
173
- $f.Text = $env:AI_VAULT_DLG_TITLE
174
- $f.Width = 480; $f.Height = 200; $f.StartPosition = 'CenterScreen'
175
- $f.TopMost = $true; $f.FormBorderStyle = 'FixedDialog'; $f.MaximizeBox = $false
176
- $lbl = New-Object System.Windows.Forms.Label
177
- $lbl.Text = $env:AI_VAULT_DLG_TEXT; $lbl.Left = 12; $lbl.Top = 12; $lbl.Width = 440; $lbl.Height = 60
178
- $f.Controls.Add($lbl)
179
- $box = New-Object System.Windows.Forms.TextBox
180
- $box.Left = 12; $box.Top = 80; $box.Width = 440
181
- if ($env:AI_VAULT_DLG_SECRET -eq '1') { $box.UseSystemPasswordChar = $true }
182
- $f.Controls.Add($box)
183
- $ok = New-Object System.Windows.Forms.Button
184
- $ok.Text = 'OK'; $ok.DialogResult = 'OK'; $ok.Left = 280; $ok.Top = 115; $f.AcceptButton = $ok
185
- $cancel = New-Object System.Windows.Forms.Button
186
- $cancel.Text = $env:AI_VAULT_DLG_CANCEL; $cancel.DialogResult = 'Cancel'; $cancel.Left = 370; $cancel.Top = 115; $f.CancelButton = $cancel
187
- $f.Controls.Add($ok); $f.Controls.Add($cancel)
188
- $f.Add_Shown({ $box.Focus() })
189
- if ($f.ShowDialog() -eq 'OK') { [Console]::Out.Write($box.Text); exit 0 } else { exit 1 }
195
+ $ErrorActionPreference = 'Stop'
196
+ try {
197
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing
198
+ $f = New-Object System.Windows.Forms.Form
199
+ $f.Text = $env:AI_VAULT_DLG_TITLE
200
+ $f.Width = 480; $f.Height = 200; $f.StartPosition = 'CenterScreen'
201
+ $f.TopMost = $true; $f.FormBorderStyle = 'FixedDialog'; $f.MaximizeBox = $false
202
+ $lbl = New-Object System.Windows.Forms.Label
203
+ $lbl.Text = $env:AI_VAULT_DLG_TEXT; $lbl.Left = 12; $lbl.Top = 12; $lbl.Width = 440; $lbl.Height = 60
204
+ $f.Controls.Add($lbl)
205
+ $box = New-Object System.Windows.Forms.TextBox
206
+ $box.Left = 12; $box.Top = 80; $box.Width = 440
207
+ if ($env:AI_VAULT_DLG_SECRET -eq '1') { $box.UseSystemPasswordChar = $true }
208
+ $f.Controls.Add($box)
209
+ $ok = New-Object System.Windows.Forms.Button
210
+ $ok.Text = 'OK'; $ok.DialogResult = 'OK'; $ok.Left = 280; $ok.Top = 115; $f.AcceptButton = $ok
211
+ $cancel = New-Object System.Windows.Forms.Button
212
+ $cancel.Text = $env:AI_VAULT_DLG_CANCEL; $cancel.DialogResult = 'Cancel'; $cancel.Left = 370; $cancel.Top = 115; $f.CancelButton = $cancel
213
+ $f.Controls.Add($ok); $f.Controls.Add($cancel)
214
+ $f.Add_Shown({ $box.Focus() })
215
+ if ($f.ShowDialog() -eq 'OK') {
216
+ $bytes = [System.Text.Encoding]::UTF8.GetBytes($box.Text)
217
+ $stdout = [Console]::OpenStandardOutput()
218
+ $stdout.Write($bytes, 0, $bytes.Length); $stdout.Flush()
219
+ exit 0
220
+ }
221
+ exit 1
222
+ } catch {
223
+ [Console]::Error.Write($_)
224
+ exit 2
225
+ }
190
226
  "#;
191
227
 
228
+ // A MessageBox has no top-most flag of its own, so it is owned by an
229
+ // invisible one that has: an approval hiding behind other windows reads as
230
+ // a hang. The default button stays "No".
192
231
  const CONFIRM: &str = r#"
193
- Add-Type -AssemblyName System.Windows.Forms, System.Drawing
194
- $msg = $env:AI_VAULT_DLG_TEXT
195
- $r = [System.Windows.Forms.MessageBox]::Show($msg, $env:AI_VAULT_DLG_TITLE, 'YesNo', 'Warning', 'Button2')
196
- if ($r -eq 'Yes') { exit 0 } else { exit 1 }
232
+ $ErrorActionPreference = 'Stop'
233
+ try {
234
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing
235
+ $owner = New-Object System.Windows.Forms.Form
236
+ $owner.TopMost = $true; $owner.Opacity = 0; $owner.ShowInTaskbar = $false
237
+ $owner.StartPosition = 'CenterScreen'; $owner.Width = 1; $owner.Height = 1
238
+ $owner.Show()
239
+ $r = [System.Windows.Forms.MessageBox]::Show($owner, $env:AI_VAULT_DLG_TEXT, $env:AI_VAULT_DLG_TITLE, 'YesNo', 'Warning', 'Button2')
240
+ $owner.Close()
241
+ if ($r -eq 'Yes') { exit 0 }
242
+ exit 1
243
+ } catch {
244
+ [Console]::Error.Write($_)
245
+ exit 2
246
+ }
197
247
  "#;
198
248
 
249
+ /// Windows PowerShell by its full path. The window takes the master
250
+ /// password, so the bare name is not left for a PATH entry or a working
251
+ /// directory to answer to.
252
+ fn powershell_exe() -> PathBuf {
253
+ std::env::var_os("SystemRoot")
254
+ .map(PathBuf::from)
255
+ .map(|root| root.join("System32").join("WindowsPowerShell").join("v1.0").join("powershell.exe"))
256
+ .unwrap_or_else(|| PathBuf::from("powershell"))
257
+ }
258
+
199
259
  struct Out {
200
260
  spawned: bool,
201
261
  code: i32,
@@ -203,8 +263,20 @@ if ($r -eq 'Yes') { exit 0 } else { exit 1 }
203
263
  stderr: String,
204
264
  }
205
265
 
266
+ /// Read a pipe to its end on its own thread: a chatty start must not block
267
+ /// on a full pipe while the window is open.
268
+ fn drain<R: Read + Send + 'static>(pipe: Option<R>) -> JoinHandle<String> {
269
+ std::thread::spawn(move || {
270
+ let mut bytes = Vec::new();
271
+ if let Some(mut pipe) = pipe {
272
+ let _ = pipe.read_to_end(&mut bytes);
273
+ }
274
+ String::from_utf8_lossy(&bytes).into_owned()
275
+ })
276
+ }
277
+
206
278
  fn powershell(script: &str, title: &str, text: &str, secret: bool) -> Out {
207
- let mut cmd = Command::new("powershell");
279
+ let mut cmd = Command::new(powershell_exe());
208
280
  cmd.args(["-NoProfile", "-NonInteractive", "-STA", "-Command", script])
209
281
  .env("AI_VAULT_DLG_TITLE", title)
210
282
  .env("AI_VAULT_DLG_TEXT", text)
@@ -213,20 +285,46 @@ if ($r -eq 'Yes') { exit 0 } else { exit 1 }
213
285
  .stdin(Stdio::null())
214
286
  .stdout(Stdio::piped())
215
287
  .stderr(Stdio::piped());
216
- let _ = DIALOG_SECONDS; // the dialog is modal for the user, not us
217
- match cmd.output() {
218
- Ok(out) => Out {
219
- spawned: true,
220
- code: out.status.code().unwrap_or(-1),
221
- stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
222
- stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
223
- },
224
- Err(_) => Out { spawned: false, code: 127, stdout: String::new(), stderr: String::new() },
288
+ let unspawned = || Out {
289
+ spawned: false,
290
+ code: 127,
291
+ stdout: String::new(),
292
+ stderr: String::new(),
293
+ };
294
+ let mut child = match cmd.spawn() {
295
+ Ok(child) => child,
296
+ Err(_) => return unspawned(),
297
+ };
298
+ let stdout = drain(child.stdout.take());
299
+ let stderr = drain(child.stderr.take());
300
+ // A window nobody answers must not hold the caller forever, exactly as
301
+ // zenity's --timeout does not: after DIALOG_SECONDS it is ours to close,
302
+ // and closing it is a cancel. (Windows has no `giving up after`.)
303
+ let deadline = Instant::now() + Duration::from_secs(DIALOG_SECONDS as u64);
304
+ let status = loop {
305
+ match child.try_wait() {
306
+ Ok(Some(status)) => break Some(status),
307
+ Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)),
308
+ _ => {
309
+ let _ = child.kill();
310
+ let _ = child.wait();
311
+ break None;
312
+ }
313
+ }
314
+ };
315
+ let stdout = stdout.join().unwrap_or_default();
316
+ let stderr = stderr.join().unwrap_or_default();
317
+ match status {
318
+ None => Out { spawned: true, code: 1, stdout, stderr },
319
+ Some(status) => Out { spawned: true, code: status.code().unwrap_or(-1), stdout, stderr },
225
320
  }
226
321
  }
227
322
 
323
+ /// Exit 1 with nothing on stderr is the user's cancel. Anything else means
324
+ /// no answer came out of a window: our own exit 2, a script PowerShell
325
+ /// could not even parse (exit 1, with the error on stderr), or a crash.
228
326
  fn failed(out: &Out) -> bool {
229
- !out.spawned || (out.code != 0 && out.code != 1)
327
+ !out.spawned || (out.code != 0 && out.code != 1) || (out.code == 1 && !out.stderr.trim().is_empty())
230
328
  }
231
329
 
232
330
  pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
@@ -258,6 +356,53 @@ if ($r -eq 'Yes') { exit 0 } else { exit 1 }
258
356
  }
259
357
  Answer::Value(out.code == 0)
260
358
  }
359
+
360
+ /// Whether this process may show a window at all. Only the interactive
361
+ /// session's window station (`WinSta0`) is visible; a service, a scheduled
362
+ /// task that runs without a logged-on user, or an sshd session gets a
363
+ /// `Service-0x0-…` station instead, where a dialog would open onto a
364
+ /// desktop nobody sees and never be answered.
365
+ pub fn has_display() -> bool {
366
+ // USEROBJECTFLAGS, as user32 lays it out: two BOOLs and a DWORD.
367
+ #[repr(C)]
368
+ #[derive(Default)]
369
+ struct UserObjectFlags {
370
+ f_inherit: i32,
371
+ f_reserved: i32,
372
+ dw_flags: u32,
373
+ }
374
+ const UOI_FLAGS: i32 = 1;
375
+ const WSF_VISIBLE: u32 = 0x0001;
376
+ #[link(name = "user32")]
377
+ extern "system" {
378
+ fn GetProcessWindowStation() -> *mut core::ffi::c_void;
379
+ fn GetUserObjectInformationW(
380
+ hobj: *mut core::ffi::c_void,
381
+ index: i32,
382
+ info: *mut core::ffi::c_void,
383
+ len: u32,
384
+ needed: *mut u32,
385
+ ) -> i32;
386
+ }
387
+ // SAFETY: two Win32 queries against the calling process's own window
388
+ // station; every pointer is either handed out by the OS or a live local.
389
+ unsafe {
390
+ let station = GetProcessWindowStation();
391
+ if station.is_null() {
392
+ return false;
393
+ }
394
+ let mut flags = UserObjectFlags::default();
395
+ let mut needed: u32 = 0;
396
+ let ok = GetUserObjectInformationW(
397
+ station,
398
+ UOI_FLAGS,
399
+ &mut flags as *mut UserObjectFlags as *mut core::ffi::c_void,
400
+ std::mem::size_of::<UserObjectFlags>() as u32,
401
+ &mut needed,
402
+ );
403
+ ok != 0 && flags.dw_flags & WSF_VISIBLE != 0
404
+ }
405
+ }
261
406
  }
262
407
 
263
408
  #[cfg(not(any(target_os = "macos", target_os = "windows")))]
@@ -532,7 +677,9 @@ mod tests {
532
677
  assert!(cut.ends_with('…'));
533
678
  }
534
679
 
680
+ // The rest of this file's helpers exist only where zenity does.
535
681
  #[test]
682
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
536
683
  fn gtk_diagnostics_are_not_failures() {
537
684
  assert!(is_gtk_diagnostic("(zenity:1234): Gtk-WARNING **: cannot open display"));
538
685
  assert!(!is_gtk_diagnostic("zenity: command not found"));
@@ -540,6 +687,7 @@ mod tests {
540
687
  }
541
688
 
542
689
  #[test]
690
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
543
691
  fn failed_spawn_and_dead_display_are_no_ui() {
544
692
  let missing = Zenity { spawned: false, code: 127, stdout: String::new(), stderr: String::new() };
545
693
  assert!(failed_to_open(&missing));
@@ -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 with the host's secret. Called before every save.
90
- pub fn sign(&mut self, host_secret: Option<&str>) {
91
- self.mac = host_secret.map(|secret| {
92
- use hmac::{Hmac, Mac};
93
- let mut hasher = <Hmac<sha2::Sha256> as Mac>::new_from_slice(secret.as_bytes())
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 a process holding `host_secret`.
101
- /// A session with no mac at all is only valid as the `never`-mode session.
102
- pub fn verifies(&self, host_secret: Option<&str>) -> bool {
103
- let (Some(secret), Some(mac)) = (host_secret, self.mac.as_deref()) else {
104
- // The only legitimate unsigned session is the machine-wide one.
105
- return self.mac.is_none() && host_secret.is_none();
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(secret.as_bytes()) else {
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
- // Constant-time compare is not required for a 256-bit tag, but cheap.
114
- expected.len() == mac.len() && expected.bytes().zip(mac.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0
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, host_secret: Option<&str>) -> Result<(), String> {
201
+ pub fn save(&self, paths: &Paths, signer: &Signer) -> Result<(), String> {
156
202
  let mut signed = self.clone();
157
- signed.sign(host_secret);
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
- if !session.verifies(host_secret) {
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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaolikt/ai-vault",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable, Linux/macOS/Windows) plus the pi-ai-vault extension for pi and omp.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,9 +33,9 @@
33
33
  "access": "public"
34
34
  },
35
35
  "optionalDependencies": {
36
- "@xiaolikt/ai-vault-linux-x64": "0.11.0",
37
- "@xiaolikt/ai-vault-linux-arm64": "0.11.0",
38
- "@xiaolikt/ai-vault-win32-x64": "0.11.0"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.12.1",
37
+ "@xiaolikt/ai-vault-linux-arm64": "0.12.1",
38
+ "@xiaolikt/ai-vault-win32-x64": "0.12.1"
39
39
  },
40
40
  "files": [
41
41
  "bin",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store, live Bitwarden and Ente Auth. Works in pi and in omp (the omp fork reads the same manifest).",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "security"
26
26
  ],
27
27
  "dependencies": {
28
- "@xiaolikt/ai-vault": "0.11.0"
28
+ "@xiaolikt/ai-vault": "0.12.1"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",