@xiaolikt/ai-vault 0.12.2 → 0.12.4

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.
@@ -2,7 +2,8 @@
2
2
  //!
3
3
  //! Linux zenity (X11 or Wayland)
4
4
  //! macOS osascript (a native dialog, hidden answer for secrets)
5
- //! Windows PowerShell + WinForms (a native dialog, PasswordChar for secrets)
5
+ //! Windows a small WinForms program of our own (`windows/dialog.cs`), which
6
+ //! follows the display and the user's theme
6
7
  //!
7
8
  //! When no window can open at all, the caller gets `NoUi` and the host UI
8
9
  //! (pi/omp prompt) takes over. Cancel and our own timeout end the prompt here:
@@ -170,199 +171,226 @@ mod mac {
170
171
 
171
172
  // -------------------------------------------------------------- Windows
172
173
 
174
+ // The windows are their own small program: `windows/dialog.cs`, a WinForms
175
+ // binary that `build.rs` compiles with the C# compiler Windows ships. It reads
176
+ // one JSON request on the stdin it inherits (never a console of its own) and
177
+ // writes one JSON answer:
178
+ //
179
+ // {"kind":"password"|"text"|"confirm","title":…,"label":…,"mask":bool,
180
+ // "ok":…,"cancel":…,"show":…,"allow":…,"deny":…}
181
+ // -> {"ok":bool,"cancelled":bool,"value":"…","on":"a screen"|""}
182
+ //
183
+ // It used to be PowerShell scripts, about two seconds a window: loading the
184
+ // assemblies and compiling the DPI helper for every prompt. The program reads
185
+ // the palette from the settings Windows already keeps and opens in about
186
+ // 150 ms. Without it (an older install, a platform package built before it)
187
+ // the scripts below are used again.
188
+
173
189
  #[cfg(target_os = "windows")]
174
190
  mod win {
175
- use super::{Answer, DIALOG_SECONDS};
176
- use std::io::Read;
177
- use std::path::PathBuf;
178
- use std::process::{Command, Stdio};
179
- use std::thread::JoinHandle;
180
- use std::time::{Duration, Instant};
181
-
182
- // WinForms from PowerShell: no extra dependency, and PasswordChar can hide
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.
194
- const PREAMBLE: &str = r#"
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
- }
226
- "#;
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".
231
- const CONFIRM: &str = r#"
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
- }
247
- "#;
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"))
191
+ use super::DIALOG_SECONDS;
192
+
193
+ /// Where `build.rs` leaves the dialog program, beside the CLI.
194
+ const PROGRAM: &str = "dialog.exe";
195
+
196
+ /// What a window is for.
197
+ #[derive(Clone, Copy, PartialEq)]
198
+ enum Kind {
199
+ /// A password: bullets over a field that keeps the IME, and a link to show it.
200
+ Secret,
201
+ /// One line of text, in the clear.
202
+ Text,
203
+ /// Yes or no, with both buttons weighing the same.
204
+ Confirm,
205
+ }
206
+
207
+ impl Kind {
208
+ fn name(self) -> &'static str {
209
+ match self {
210
+ Kind::Secret => "password",
211
+ Kind::Text => "text",
212
+ Kind::Confirm => "confirm",
213
+ }
214
+ }
257
215
  }
258
216
 
259
- struct Out {
260
- spawned: bool,
261
- code: i32,
262
- stdout: String,
263
- stderr: String,
217
+ /// The words in the window, in the user's language.
218
+ struct Words {
219
+ title: String,
220
+ label: String,
221
+ ok: &'static str,
222
+ cancel: &'static str,
223
+ show: &'static str,
224
+ allow: &'static str,
225
+ deny: &'static str,
226
+ }
227
+
228
+ fn words(title: &str, label: &str) -> Words {
229
+ Words {
230
+ title: title.to_string(),
231
+ label: label.to_string(),
232
+ ok: crate::i18n::tr("OK", "确定"),
233
+ cancel: crate::i18n::tr("Cancel", "取消"),
234
+ show: crate::i18n::tr("Show", "显示"),
235
+ allow: crate::i18n::tr("Allow", "允许"),
236
+ deny: crate::i18n::tr("Deny", "拒绝"),
237
+ }
264
238
  }
265
239
 
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);
240
+ fn json_string(text: &str) -> String {
241
+ let mut out = String::with_capacity(text.len() + 2);
242
+ out.push('"');
243
+ for c in text.chars() {
244
+ match c {
245
+ '"' => out.push_str("\\\""),
246
+ '\\' => out.push_str("\\\\"),
247
+ '\n' => out.push_str("\\n"),
248
+ '\r' => out.push_str("\\r"),
249
+ '\t' => out.push_str("\\t"),
250
+ c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
251
+ c => out.push(c),
273
252
  }
274
- String::from_utf8_lossy(&bytes).into_owned()
275
- })
253
+ }
254
+ out.push('"');
255
+ out
256
+ }
257
+
258
+ fn request(kind: Kind, w: &Words, mask: bool) -> String {
259
+ format!(
260
+ "{{\"kind\":{},\"title\":{},\"label\":{},\"mask\":{},\"ok\":{},\"cancel\":{},\"show\":{},\"allow\":{},\"deny\":{}}}",
261
+ json_string(kind.name()),
262
+ json_string(&w.title),
263
+ json_string(&w.label),
264
+ mask,
265
+ json_string(w.ok),
266
+ json_string(w.cancel),
267
+ json_string(w.show),
268
+ json_string(w.allow),
269
+ json_string(w.deny),
270
+ )
276
271
  }
277
272
 
278
- fn powershell(script: &str, title: &str, text: &str, secret: bool) -> Out {
279
- let mut cmd = Command::new(powershell_exe());
280
- cmd.args(["-NoProfile", "-NonInteractive", "-STA", "-Command", script])
281
- .env("AI_VAULT_DLG_TITLE", title)
282
- .env("AI_VAULT_DLG_TEXT", text)
283
- .env("AI_VAULT_DLG_SECRET", if secret { "1" } else { "0" })
284
- .env("AI_VAULT_DLG_CANCEL", crate::i18n::tr("Cancel", "取消"))
285
- .stdin(Stdio::null())
286
- .stdout(Stdio::piped())
287
- .stderr(Stdio::piped());
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(),
273
+ /// A string field out of the program's flat JSON answer.
274
+ fn field(json: &str, key: &str) -> Option<String> {
275
+ let at = json.find(&format!("\"{key}\":"))? + key.len() + 3;
276
+ let rest = &json[at..];
277
+ let Some(body) = rest.strip_prefix('"') else {
278
+ if rest.starts_with("true") {
279
+ return Some("true".to_string());
280
+ }
281
+ if rest.starts_with("false") {
282
+ return Some("false".to_string());
283
+ }
284
+ return None;
297
285
  };
298
- let stdout = drain(child.stdout.take());
299
- let stderr = drain(child.stderr.take());
286
+ let mut out = String::new();
287
+ let mut chars = body.chars();
288
+ while let Some(c) = chars.next() {
289
+ match c {
290
+ '"' => return Some(out),
291
+ '\\' => match chars.next() {
292
+ Some('n') => out.push('\n'),
293
+ Some('r') => out.push('\r'),
294
+ Some('t') => out.push('\t'),
295
+ Some('u') => {
296
+ let hex: String = chars.by_ref().take(4).collect();
297
+ if let Ok(code) = u32::from_str_radix(&hex, 16) {
298
+ if let Some(c) = char::from_u32(code) {
299
+ out.push(c);
300
+ }
301
+ }
302
+ }
303
+ Some(c) => out.push(c),
304
+ None => break,
305
+ },
306
+ c => out.push(c),
307
+ }
308
+ }
309
+ None
310
+ }
311
+
312
+ /// The dialog program, next to this executable, when `build.rs` put it there.
313
+ fn program() -> Option<std::path::PathBuf> {
314
+ let exe = std::env::current_exe().ok()?;
315
+ let beside = exe.parent()?.join(PROGRAM);
316
+ beside.is_file().then_some(beside)
317
+ }
318
+
319
+ fn wait(child: &mut std::process::Child) -> Option<bool> {
320
+ use std::time::{Duration, Instant};
300
321
  // 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`.)
322
+ // zenity's --timeout does not. Closing it is a cancel.
303
323
  let deadline = Instant::now() + Duration::from_secs(DIALOG_SECONDS as u64);
304
- let status = loop {
324
+ loop {
305
325
  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)),
326
+ Ok(Some(_)) => return Some(true),
327
+ Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
308
328
  _ => {
309
329
  let _ = child.kill();
310
330
  let _ = child.wait();
311
- break None;
331
+ return None;
312
332
  }
313
333
  }
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 },
320
334
  }
321
335
  }
322
336
 
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.
326
- fn failed(out: &Out) -> bool {
327
- !out.spawned || (out.code != 0 && out.code != 1) || (out.code == 1 && !out.stderr.trim().is_empty())
328
- }
329
-
330
- pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
331
- let out = powershell(PREAMBLE, title, label, true);
332
- if failed(&out) {
333
- return Answer::NoUi;
337
+ /// Ask the dialog program. `Ok(None)` means it could not run or reported no
338
+ /// screen: the caller decides what to do instead.
339
+ fn ask(kind: Kind, w: &Words, mask: bool) -> Option<super::Answer<String>> {
340
+ use std::io::{Read, Write};
341
+ use std::process::{Command, Stdio};
342
+ use super::Answer;
343
+ let program = program()?;
344
+ let mut child = Command::new(&program)
345
+ .stdin(Stdio::piped())
346
+ .stdout(Stdio::piped())
347
+ .stderr(Stdio::piped())
348
+ .spawn()
349
+ .ok()?;
350
+ let body = request(kind, w, mask);
351
+ if let Some(mut stdin) = child.stdin.take() {
352
+ let _ = stdin.write_all(body.as_bytes());
334
353
  }
335
- if out.code != 0 || out.stdout.is_empty() {
336
- return Answer::Cancelled;
354
+ if wait(&mut child).is_none() {
355
+ return Some(Answer::Cancelled);
337
356
  }
338
- Answer::Value(out.stdout)
339
- }
340
-
341
- pub fn prompt_text(title: &str, label: &str) -> Answer<String> {
342
- let out = powershell(PREAMBLE, title, label, false);
343
- if failed(&out) {
344
- return Answer::NoUi;
357
+ let mut out = String::new();
358
+ child.stdout.take()?.read_to_string(&mut out).ok()?;
359
+ if field(&out, "on").as_deref() == Some("") {
360
+ return None; // no screen
345
361
  }
346
- if out.code != 0 {
347
- return Answer::Cancelled;
362
+ match field(&out, "ok").as_deref() {
363
+ Some("true") => Some(Answer::Value(field(&out, "value").unwrap_or_default())),
364
+ _ => Some(Answer::Cancelled),
348
365
  }
349
- Answer::Value(out.stdout)
350
366
  }
351
367
 
352
- pub fn confirm(title: &str, message: &str) -> Answer<bool> {
353
- let out = powershell(CONFIRM, title, message, false);
354
- if failed(&out) {
355
- return Answer::NoUi;
368
+ pub fn prompt_secret(title: &str, label: &str, revealable: bool) -> super::Answer<String> {
369
+ ask(Kind::Secret, &words(title, label), revealable).unwrap_or(super::Answer::NoUi)
370
+ }
371
+
372
+ pub fn prompt_text(title: &str, label: &str) -> super::Answer<String> {
373
+ ask(Kind::Text, &words(title, label), false).unwrap_or(super::Answer::NoUi)
374
+ }
375
+
376
+ pub fn confirm(title: &str, message: &str) -> super::Answer<bool> {
377
+ match ask(Kind::Confirm, &words(title, message), false) {
378
+ Some(super::Answer::Value(_)) => super::Answer::Value(true),
379
+ Some(super::Answer::Cancelled) => super::Answer::Cancelled,
380
+ Some(super::Answer::NoUi) | None => super::Answer::NoUi,
356
381
  }
357
- Answer::Value(out.code == 0)
358
382
  }
359
383
 
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.
384
+ /// Whether this process may show a window at all: a window station that is
385
+ /// not visible, or an input desktop it cannot open, means a service, a
386
+ /// scheduled task without a logged-on user, or an sshd session.
365
387
  pub fn has_display() -> bool {
388
+ use std::process::{Command, Stdio};
389
+ if let Some(program) = program() {
390
+ if let Ok(out) = Command::new(program).arg("--probe").stdin(Stdio::null()).output() {
391
+ return String::from_utf8_lossy(&out.stdout) == "on";
392
+ }
393
+ }
366
394
  // USEROBJECTFLAGS, as user32 lays it out: two BOOLs and a DWORD.
367
395
  #[repr(C)]
368
396
  #[derive(Default)]
@@ -383,9 +411,13 @@ try {
383
411
  len: u32,
384
412
  needed: *mut u32,
385
413
  ) -> i32;
414
+ fn OpenInputDesktop(flags: u32, inherit: i32, access: u32) -> *mut core::ffi::c_void;
415
+ fn CloseDesktop(desktop: *mut core::ffi::c_void) -> i32;
386
416
  }
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.
417
+ const DESKTOP_READOBJECTS: u32 = 0x0001;
418
+ // SAFETY: Win32 queries against the calling process's own window station
419
+ // and the input desktop; every pointer is handed out by the OS or is a
420
+ // live local.
389
421
  unsafe {
390
422
  let station = GetProcessWindowStation();
391
423
  if station.is_null() {
@@ -400,7 +432,15 @@ try {
400
432
  std::mem::size_of::<UserObjectFlags>() as u32,
401
433
  &mut needed,
402
434
  );
403
- ok != 0 && flags.dw_flags & WSF_VISIBLE != 0
435
+ if ok == 0 || flags.dw_flags & WSF_VISIBLE == 0 {
436
+ return false;
437
+ }
438
+ let desktop = OpenInputDesktop(0, 0, DESKTOP_READOBJECTS);
439
+ if desktop.is_null() {
440
+ return false;
441
+ }
442
+ CloseDesktop(desktop);
443
+ true
404
444
  }
405
445
  }
406
446
  }
@@ -550,14 +590,17 @@ pub fn for_dialog(value: &str, max: usize) -> String {
550
590
  }
551
591
 
552
592
  /// Secret entry. Empty and cancel are both "no value".
553
- pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
593
+ /// A password. `revealable` puts a link in the window that shows what was typed:
594
+ /// right for a master password (a typo is expensive), not for an entry's own
595
+ /// password (it is read back with `vault_get` anyway).
596
+ pub fn prompt_secret(title: &str, label: &str, revealable: bool) -> Answer<String> {
554
597
  #[cfg(target_os = "macos")]
555
598
  {
556
599
  return mac::prompt_secret(title, label);
557
600
  }
558
601
  #[cfg(target_os = "windows")]
559
602
  {
560
- return win::prompt_secret(title, label);
603
+ return win::prompt_secret(title, label, revealable);
561
604
  }
562
605
  #[cfg(not(any(target_os = "macos", target_os = "windows")))]
563
606
  prompt_secret_zenity(title, label)