@xiaolikt/ai-vault 0.0.0-stage → 0.5.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.
Files changed (41) hide show
  1. package/Cargo.lock +784 -0
  2. package/Cargo.toml +8 -0
  3. package/LICENSE +21 -0
  4. package/README.md +244 -2
  5. package/bin/ai-vault.cjs +71 -0
  6. package/crates/ai-vault/Cargo.toml +26 -0
  7. package/crates/ai-vault/src/audit.rs +77 -0
  8. package/crates/ai-vault/src/cli.rs +1129 -0
  9. package/crates/ai-vault/src/config.rs +77 -0
  10. package/crates/ai-vault/src/crypto.rs +265 -0
  11. package/crates/ai-vault/src/dialog.rs +222 -0
  12. package/crates/ai-vault/src/import.rs +175 -0
  13. package/crates/ai-vault/src/main.rs +22 -0
  14. package/crates/ai-vault/src/paths.rs +68 -0
  15. package/crates/ai-vault/src/session.rs +280 -0
  16. package/crates/ai-vault/src/store.rs +219 -0
  17. package/install.sh +21 -0
  18. package/package.json +76 -5
  19. package/packages/pi-ai-vault/README.md +62 -0
  20. package/packages/pi-ai-vault/package.json +47 -0
  21. package/packages/pi-ai-vault/src/bitwarden.ts +1482 -0
  22. package/packages/pi-ai-vault/src/cli.ts +171 -0
  23. package/packages/pi-ai-vault/src/host.ts +76 -0
  24. package/packages/pi-ai-vault/src/import-map.ts +91 -0
  25. package/packages/pi-ai-vault/src/index.ts +976 -0
  26. package/packages/pi-ai-vault/src/prompt.ts +195 -0
  27. package/packages/pi-ai-vault/src/scrub.ts +157 -0
  28. package/test/cli.sh +135 -0
  29. package/test/npm.sh +70 -0
  30. package/test/smoke.sh +77 -0
  31. package/tests/bitwarden-tools.test.mjs +330 -0
  32. package/tests/helpers.mjs +131 -0
  33. package/tests/import-map.test.mjs +74 -0
  34. package/tests/mocks/bin/bw +41 -0
  35. package/tests/mocks/bin/wl-copy +15 -0
  36. package/tests/mocks/bin/wl-paste +9 -0
  37. package/tests/mocks/bin/zenity +51 -0
  38. package/tests/prompt.test.mjs +200 -0
  39. package/tests/register.test.mjs +48 -0
  40. package/tests/scrub.test.mjs +98 -0
  41. package/tests/vault-cli.test.mjs +217 -0
@@ -0,0 +1,77 @@
1
+ //! Machine-wide unlock policy: how often the vault asks for the master
2
+ //! password. Switching the mode always re-verifies the master password.
3
+
4
+ use serde::{Deserialize, Serialize};
5
+ use std::fs;
6
+
7
+ use crate::crypto;
8
+ use crate::paths::Paths;
9
+
10
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11
+ #[serde(rename_all = "kebab-case")]
12
+ pub enum UnlockMode {
13
+ /// Never ask again: the key lives in the store directory, readable by this
14
+ /// user, so agents can read secrets without any window.
15
+ Never,
16
+ /// Ask again after `hours`, counted from the unlock (not from the last use).
17
+ Time,
18
+ /// Ask once per agent session; the token dies when the session ends.
19
+ Session,
20
+ }
21
+
22
+ impl UnlockMode {
23
+ pub fn parse(text: &str) -> Option<UnlockMode> {
24
+ match text.trim().to_lowercase().as_str() {
25
+ "never" | "no-password" | "none" | "off" => Some(UnlockMode::Never),
26
+ "time" | "hours" => Some(UnlockMode::Time),
27
+ "session" | "on" => Some(UnlockMode::Session),
28
+ _ => None,
29
+ }
30
+ }
31
+
32
+ pub fn as_str(self) -> &'static str {
33
+ match self {
34
+ UnlockMode::Never => "never",
35
+ UnlockMode::Time => "time",
36
+ UnlockMode::Session => "session",
37
+ }
38
+ }
39
+ }
40
+
41
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
42
+ pub struct UnlockPolicy {
43
+ pub mode: UnlockMode,
44
+ /// `Time` mode only: hours between password prompts.
45
+ #[serde(default = "default_hours")]
46
+ pub hours: i64,
47
+ }
48
+
49
+ fn default_hours() -> i64 {
50
+ 8
51
+ }
52
+
53
+ impl Default for UnlockPolicy {
54
+ fn default() -> Self {
55
+ UnlockPolicy { mode: UnlockMode::Session, hours: default_hours() }
56
+ }
57
+ }
58
+
59
+ #[derive(Debug, Clone, Serialize, Deserialize, Default)]
60
+ pub struct Config {
61
+ #[serde(default)]
62
+ pub unlock: UnlockPolicy,
63
+ }
64
+
65
+ /// A missing or unreadable config means the default policy: ask once per
66
+ /// session. A broken file must not lock anyone out of their vault.
67
+ pub fn load(paths: &Paths) -> Config {
68
+ match fs::read_to_string(paths.config()) {
69
+ Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
70
+ Err(_) => Config::default(),
71
+ }
72
+ }
73
+
74
+ pub fn save(paths: &Paths, config: &Config) -> Result<(), String> {
75
+ let bytes = serde_json::to_vec_pretty(config).map_err(|e| format!("cannot serialize config: {e}"))?;
76
+ crypto::write_atomic(&paths.config(), &bytes)
77
+ }
@@ -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
+ }