@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,942 @@
1
+ //! Command line surface. Every subcommand is one process: read the store,
2
+ //! prove the session token, do one thing, exit. The pi/omp extension calls
3
+ //! these commands and never links against the encryption itself.
4
+
5
+ use std::io::{self, BufRead, Read};
6
+ use std::os::unix::fs::PermissionsExt;
7
+ use std::path::PathBuf;
8
+
9
+ use clap::{Parser, Subcommand};
10
+ use serde_json::json;
11
+
12
+ use crate::crypto::{self, Kdf};
13
+ use crate::dialog::{self, Answer};
14
+ use crate::import;
15
+ use crate::paths::{Paths, GRANT_MS_DEFAULT, GRANT_MS_MAX, IDLE_MS_DEFAULT};
16
+ use crate::session::{self, Session, StoreLock};
17
+ use crate::store::{self, Draft, Item};
18
+ use crate::{audit, store::ItemSummary};
19
+
20
+ #[derive(Parser, Debug)]
21
+ #[command(
22
+ name = "ai-vault",
23
+ version,
24
+ about = "Machine-wide encrypted secret store shared by AI coding agents",
25
+ long_about = "One encrypted store per machine (~/.ai-vault), shared by every agent.\n\
26
+ The master password goes through a desktop dialog, never through the\n\
27
+ conversation. `unlock` returns a short-lived token; later calls pass it\n\
28
+ back with --token (or AI_VAULT_TOKEN)."
29
+ )]
30
+ struct Cli {
31
+ /// Store directory (default: $AI_VAULT_DIR or ~/.ai-vault)
32
+ #[arg(long, global = true, env = "AI_VAULT_DIR", value_name = "DIR")]
33
+ dir: Option<PathBuf>,
34
+ /// Machine-readable JSON on stdout
35
+ #[arg(long, global = true)]
36
+ json: bool,
37
+ #[command(subcommand)]
38
+ cmd: Cmd,
39
+ }
40
+
41
+ #[derive(Subcommand, Debug)]
42
+ enum Cmd {
43
+ /// Print the store directory
44
+ Path,
45
+ /// Create the store and a fresh session (prompts for a new master password)
46
+ Init {
47
+ /// Read the password from stdin instead of a dialog
48
+ #[arg(long)]
49
+ password_stdin: bool,
50
+ /// Who is unlocking (written to the audit log)
51
+ #[arg(long, default_value = "cli")]
52
+ requester: String,
53
+ /// Idle minutes before the session locks itself
54
+ #[arg(long, value_name = "MIN")]
55
+ idle_min: Option<i64>,
56
+ },
57
+ /// Unlock the store and print a session token
58
+ Unlock {
59
+ /// Read the password from stdin instead of a dialog
60
+ #[arg(long)]
61
+ password_stdin: bool,
62
+ /// Who is unlocking (written to the audit log and the confirm window)
63
+ #[arg(long, default_value = "cli")]
64
+ requester: String,
65
+ /// Idle minutes before the session locks itself
66
+ #[arg(long, value_name = "MIN")]
67
+ idle_min: Option<i64>,
68
+ },
69
+ /// Session state, item count, and remaining read grants
70
+ Status {
71
+ #[arg(long, env = "AI_VAULT_TOKEN")]
72
+ token: Option<String>,
73
+ },
74
+ /// Drop one session token, or every session with --all
75
+ Lock {
76
+ #[arg(long, env = "AI_VAULT_TOKEN")]
77
+ token: Option<String>,
78
+ #[arg(long)]
79
+ all: bool,
80
+ },
81
+ /// Entry metadata only (name, username, URIs) — no passwords
82
+ List {
83
+ #[arg(long, env = "AI_VAULT_TOKEN")]
84
+ token: Option<String>,
85
+ },
86
+ /// Read one entry; the user approves a window unless a grant is live
87
+ Get {
88
+ name: String,
89
+ #[arg(long, env = "AI_VAULT_TOKEN")]
90
+ token: Option<String>,
91
+ /// Why the secret is needed (shown in the confirm window)
92
+ #[arg(long)]
93
+ reason: Option<String>,
94
+ /// Read the approve/deny answer from stdin (host UI already asked)
95
+ #[arg(long)]
96
+ answer_stdin: bool,
97
+ },
98
+ /// Create or update an entry; the password is typed in a dialog
99
+ Add {
100
+ #[arg(long)]
101
+ name: String,
102
+ #[arg(long)]
103
+ username: Option<String>,
104
+ #[arg(long)]
105
+ uri: Option<String>,
106
+ #[arg(long)]
107
+ notes: Option<String>,
108
+ /// Read the password from stdin instead of a dialog
109
+ #[arg(long)]
110
+ password_stdin: bool,
111
+ /// Skip the "save this?" confirm window (the user already approved)
112
+ #[arg(long)]
113
+ yes: bool,
114
+ #[arg(long, env = "AI_VAULT_TOKEN")]
115
+ token: Option<String>,
116
+ },
117
+ /// Insert or update many entries from a JSON array on stdin (or --file)
118
+ Save {
119
+ #[arg(long, env = "AI_VAULT_TOKEN")]
120
+ token: Option<String>,
121
+ #[arg(long, value_name = "FILE")]
122
+ file: Option<PathBuf>,
123
+ /// The caller already approved this write in its own UI
124
+ #[arg(long)]
125
+ yes: bool,
126
+ },
127
+ /// Delete one entry
128
+ Remove {
129
+ name: String,
130
+ #[arg(long)]
131
+ yes: bool,
132
+ #[arg(long, env = "AI_VAULT_TOKEN")]
133
+ token: Option<String>,
134
+ },
135
+ /// Allow reads of one entry without a window for a while
136
+ Grant {
137
+ name: String,
138
+ #[arg(long, value_name = "MIN")]
139
+ minutes: Option<i64>,
140
+ #[arg(long, env = "AI_VAULT_TOKEN")]
141
+ token: Option<String>,
142
+ },
143
+ /// End grants for one entry, or all of them
144
+ Revoke {
145
+ name: Option<String>,
146
+ #[arg(long)]
147
+ all: bool,
148
+ #[arg(long, env = "AI_VAULT_TOKEN")]
149
+ token: Option<String>,
150
+ },
151
+ /// Recent audit lines (who asked for what)
152
+ Audit {
153
+ #[arg(default_value_t = 30)]
154
+ n: usize,
155
+ },
156
+ /// Import a Bitwarden JSON export (array or { items: [...] })
157
+ Import {
158
+ file: PathBuf,
159
+ #[arg(long)]
160
+ yes: bool,
161
+ #[arg(long, env = "AI_VAULT_TOKEN")]
162
+ token: Option<String>,
163
+ },
164
+ /// Diagnose paths, session directory and desktop availability
165
+ Doctor,
166
+ }
167
+
168
+ #[derive(Debug)]
169
+ enum Fault {
170
+ Error(String),
171
+ Usage(String),
172
+ /// No desktop window could be opened; the host must supply the value.
173
+ NeedsUi(&'static str),
174
+ Denied(String),
175
+ Auth(String),
176
+ }
177
+
178
+ impl Fault {
179
+ fn exit_code(&self) -> i32 {
180
+ match self {
181
+ Fault::Error(_) => 1,
182
+ Fault::Usage(_) => 2,
183
+ Fault::NeedsUi(_) => 3,
184
+ Fault::Denied(_) => 4,
185
+ Fault::Auth(_) => 5,
186
+ }
187
+ }
188
+ }
189
+
190
+ impl From<String> for Fault {
191
+ fn from(message: String) -> Self {
192
+ Fault::Error(message)
193
+ }
194
+ }
195
+
196
+ type Outcome = Result<(), Fault>;
197
+
198
+ pub fn run() -> i32 {
199
+ let cli = match Cli::try_parse() {
200
+ Ok(cli) => cli,
201
+ Err(e) => {
202
+ let _ = e.print();
203
+ return if e.use_stderr() { 2 } else { 0 };
204
+ }
205
+ };
206
+ let paths = Paths::resolve(cli.dir.clone());
207
+ migrate_legacy(&paths);
208
+ let json = cli.json;
209
+ match dispatch(cli.cmd, &paths, json) {
210
+ Ok(()) => 0,
211
+ Err(fault) => {
212
+ match &fault {
213
+ Fault::NeedsUi(step) => {
214
+ eprintln!("needs-ui: {step}");
215
+ eprintln!("no desktop window is available; the host must supply this value");
216
+ }
217
+ Fault::Usage(message) => eprintln!("ai-vault: {message}"),
218
+ Fault::Error(message) | Fault::Denied(message) | Fault::Auth(message) => {
219
+ eprintln!("ai-vault: {message}")
220
+ }
221
+ }
222
+ fault.exit_code()
223
+ }
224
+ }
225
+ }
226
+
227
+ /// One-time move from the per-agent directory the TypeScript release used
228
+ /// (~/.omp/vault). The old file is copied, not removed: rolling back to that
229
+ /// extension still works.
230
+ fn migrate_legacy(paths: &Paths) {
231
+ // Only the real default directory: AI_VAULT_DIR is an explicit choice and
232
+ // must never inherit another location's store.
233
+ if paths.store().exists() || paths.dir != crate::paths::home().join(".ai-vault") {
234
+ return;
235
+ }
236
+ let legacy = crate::paths::home().join(".omp").join("vault");
237
+ let legacy_store = legacy.join("store.json");
238
+ if !legacy_store.exists() {
239
+ return;
240
+ }
241
+ if std::fs::create_dir_all(&paths.dir).is_err() {
242
+ return;
243
+ }
244
+ if std::fs::copy(&legacy_store, paths.store()).is_err() {
245
+ return;
246
+ }
247
+ let _ = std::fs::set_permissions(&paths.store(), std::fs::Permissions::from_mode(0o600));
248
+ if legacy.join("audit.log").exists() && !paths.audit().exists() {
249
+ let _ = std::fs::copy(legacy.join("audit.log"), paths.audit());
250
+ }
251
+ eprintln!(
252
+ "ai-vault: 已把共享库从 {} 复制到 {}(旧文件保留)",
253
+ legacy.display(),
254
+ paths.dir.display()
255
+ );
256
+ }
257
+
258
+ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
259
+ let out = Out { json };
260
+ match cmd {
261
+ Cmd::Path => {
262
+ out.json_value(json!({ "path": paths.store(), "dir": paths.dir, "sessions": paths.sessions() }));
263
+ out.text(paths.store().display().to_string());
264
+ Ok(())
265
+ }
266
+ Cmd::Doctor => doctor(paths, &out),
267
+ Cmd::Init { password_stdin, requester, idle_min } => {
268
+ init(paths, &out, password_stdin, &requester, idle_ms(idle_min))
269
+ }
270
+ Cmd::Unlock { password_stdin, requester, idle_min } => {
271
+ unlock(paths, &out, password_stdin, &requester, idle_ms(idle_min))
272
+ }
273
+ Cmd::Status { token } => status(paths, &out, token),
274
+ Cmd::Lock { token, all } => lock(paths, &out, token, all),
275
+ Cmd::List { token } => list(paths, &out, token),
276
+ Cmd::Get { name, token, reason, answer_stdin } => {
277
+ get(paths, &out, token, &name, reason.as_deref(), answer_stdin)
278
+ }
279
+ Cmd::Add { name, username, uri, notes, password_stdin, yes, token } => {
280
+ add(paths, &out, token, AddRequest { name, username, uri, notes, password_stdin, yes })
281
+ }
282
+ Cmd::Save { token, file, yes } => save(paths, &out, token, file, yes),
283
+ Cmd::Remove { name, yes, token } => remove(paths, &out, token, &name, yes),
284
+ Cmd::Grant { name, minutes, token } => grant(paths, &out, token, &name, minutes),
285
+ Cmd::Revoke { name, all, token } => revoke(paths, &out, token, name.as_deref(), all),
286
+ Cmd::Audit { n } => audit_entries(paths, &out, n),
287
+ Cmd::Import { file, yes, token } => import_file(paths, &out, token, &file, yes),
288
+ }
289
+ }
290
+
291
+ struct Out {
292
+ json: bool,
293
+ }
294
+
295
+ impl Out {
296
+ fn json_value(&self, value: serde_json::Value) {
297
+ if self.json {
298
+ println!("{}", serde_json::to_string(&value).unwrap_or_else(|_| "{}".into()));
299
+ }
300
+ }
301
+
302
+ fn text(&self, text: impl AsRef<str>) {
303
+ if !self.json {
304
+ println!("{}", text.as_ref());
305
+ }
306
+ }
307
+
308
+ fn value(&self, value: serde_json::Value, human: impl FnOnce() -> String) {
309
+ if self.json {
310
+ self.json_value(value);
311
+ } else {
312
+ self.text(human());
313
+ }
314
+ }
315
+ }
316
+
317
+ fn idle_ms(minutes: Option<i64>) -> i64 {
318
+ minutes.map(|m| m.clamp(1, 600) * 60_000).unwrap_or(IDLE_MS_DEFAULT)
319
+ }
320
+
321
+ // ---------------------------------------------------------------- input
322
+
323
+ fn read_password() -> Result<String, Fault> {
324
+ let line = read_line()?;
325
+ let password = line.trim_end_matches(['\r', '\n']).to_string();
326
+ if password.is_empty() {
327
+ return Err(Fault::Usage("empty password on stdin".into()));
328
+ }
329
+ Ok(password)
330
+ }
331
+
332
+ fn read_line() -> Result<String, Fault> {
333
+ let mut line = String::new();
334
+ io::stdin()
335
+ .lock()
336
+ .read_line(&mut line)
337
+ .map_err(|e| Fault::Error(format!("cannot read stdin: {e}")))?;
338
+ Ok(line)
339
+ }
340
+
341
+ fn read_stdin_text() -> Result<String, Fault> {
342
+ let mut text = String::new();
343
+ io::stdin()
344
+ .read_to_string(&mut text)
345
+ .map_err(|e| Fault::Error(format!("cannot read stdin: {e}")))?;
346
+ Ok(text)
347
+ }
348
+
349
+ /// A yes/no answer from stdin, used when the host UI already asked the user.
350
+ fn read_approval() -> Result<bool, Fault> {
351
+ let answer = read_line()?.trim().to_lowercase();
352
+ Ok(matches!(answer.as_str(), "y" | "yes" | "allow" | "允许" | "1" | "true"))
353
+ }
354
+
355
+ fn ask_password(title: &str, label: &str) -> Result<String, Fault> {
356
+ match dialog::prompt_secret(title, label) {
357
+ Answer::Value(value) => Ok(value),
358
+ Answer::Cancelled => Err(Fault::Denied("cancelled: no password entered".into())),
359
+ Answer::NoUi => Err(Fault::NeedsUi("password")),
360
+ }
361
+ }
362
+
363
+ fn ask_text(title: &str, label: &str) -> Result<String, Fault> {
364
+ match dialog::prompt_text(title, label) {
365
+ Answer::Value(value) => Ok(value),
366
+ Answer::Cancelled => Err(Fault::Denied("cancelled".into())),
367
+ Answer::NoUi => Err(Fault::NeedsUi("text")),
368
+ }
369
+ }
370
+
371
+ // ---------------------------------------------------------------- store access
372
+
373
+ fn open_store(paths: &Paths) -> Result<crypto::StoreFile, Fault> {
374
+ crypto::read_store(&paths.store())?.ok_or_else(|| {
375
+ Fault::Error(format!("vault is not initialized — run `ai-vault init` (store: {})", paths.store().display()))
376
+ })
377
+ }
378
+
379
+ fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>, Fault> {
380
+ let key = session
381
+ .key()
382
+ .ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
383
+ crypto::open_with_key(store, &key).map_err(|e| match e {
384
+ crypto::OpenError::WrongPassword => Fault::Auth("the store does not open with this session — unlock again".into()),
385
+ crypto::OpenError::Broken(message) => Fault::Error(message),
386
+ })
387
+ }
388
+
389
+ fn load_session(paths: &Paths, token: Option<&str>) -> Result<Session, Fault> {
390
+ let token = token.filter(|t| !t.is_empty()).ok_or_else(|| {
391
+ Fault::Auth("vault is locked (no session token) — unlock first".into())
392
+ })?;
393
+ session::load(paths, token).map_err(Fault::Auth)
394
+ }
395
+
396
+ fn touch(paths: &Paths, session: &mut Session) {
397
+ session.last_active = session::now_ms();
398
+ let _ = session.prune_grants(session.last_active);
399
+ let _ = session.save(paths);
400
+ }
401
+
402
+ /// Read-modify-write under one advisory lock. The closure never opens a dialog
403
+ /// (that would block every other agent for minutes).
404
+ fn mutate<F>(paths: &Paths, session: &Session, f: F) -> Result<(), Fault>
405
+ where
406
+ F: FnOnce(&mut Vec<Item>, &str) -> Result<(), Fault>,
407
+ {
408
+ let _guard = StoreLock::acquire(paths)?;
409
+ let store = open_store(paths)?;
410
+ let mut items = items_with(session, &store)?;
411
+ let now = store::now_iso();
412
+ f(&mut items, &now)?;
413
+ let key = session
414
+ .key()
415
+ .ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
416
+ let salt = crypto::hex_to_bytes(&session.salt).ok_or_else(|| Fault::Error("session salt is corrupt".into()))?;
417
+ let sealed = crypto::seal(&salt, session.kdf.unwrap_or_default(), &key, &items)?;
418
+ let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
419
+ crypto::write_atomic(&paths.store(), &bytes)?;
420
+ Ok(())
421
+ }
422
+
423
+ // ---------------------------------------------------------------- commands
424
+
425
+ fn doctor(paths: &Paths, out: &Out) -> Outcome {
426
+ session::ensure_session_dir(paths)?;
427
+ let value = json!({
428
+ "version": env!("CARGO_PKG_VERSION"),
429
+ "dir": paths.dir,
430
+ "store": paths.store(),
431
+ "initialized": paths.store().exists(),
432
+ "sessions": paths.sessions(),
433
+ "audit": paths.audit(),
434
+ "display": dialog::has_display(),
435
+ "zenity": which("zenity"),
436
+ });
437
+ out.value(value.clone(), || {
438
+ let mut lines = Vec::new();
439
+ for (key, item) in value.as_object().into_iter().flatten() {
440
+ lines.push(format!("{key}: {}", item.as_str().map(str::to_string).unwrap_or_else(|| item.to_string())));
441
+ }
442
+ lines.join("\n")
443
+ });
444
+ Ok(())
445
+ }
446
+
447
+ fn which(program: &str) -> bool {
448
+ std::env::var_os("PATH").is_some_and(|paths| {
449
+ std::env::split_paths(&paths).any(|dir| dir.join(program).is_file())
450
+ })
451
+ }
452
+
453
+ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_ms: i64) -> Outcome {
454
+ if paths.store().exists() {
455
+ return Err(Fault::Error(format!(
456
+ "vault already initialized — {}",
457
+ paths.store().display()
458
+ )));
459
+ }
460
+ let password = if password_stdin {
461
+ read_password()?
462
+ } else {
463
+ let first = ask_password("ai-vault · 创建主密码", "至少 8 位")?;
464
+ if first.len() < 8 {
465
+ return Err(Fault::Usage("the master password must be at least 8 characters".into()));
466
+ }
467
+ let again = ask_password("ai-vault · 确认主密码", "再输入一次")?;
468
+ if again != first {
469
+ return Err(Fault::Denied("the two passwords do not match".into()));
470
+ }
471
+ first
472
+ };
473
+ if password.len() < 8 {
474
+ return Err(Fault::Usage("the master password must be at least 8 characters".into()));
475
+ }
476
+
477
+ let salt = crypto::random_bytes::<16>();
478
+ let kdf = Kdf::default();
479
+ let key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
480
+ let sealed = crypto::seal(&salt, kdf, &key, &[])?;
481
+ {
482
+ let _guard = StoreLock::acquire(paths)?;
483
+ if paths.store().exists() {
484
+ return Err(Fault::Error("vault already initialized".into()));
485
+ }
486
+ let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
487
+ crypto::write_atomic(&paths.store(), &bytes)?;
488
+ }
489
+ session::ensure_session_dir(paths)?;
490
+ let session = Session::new(requester, idle_ms, &sealed, &key);
491
+ session.save(paths)?;
492
+ audit::append(&paths.audit(), requester, "init", None, None);
493
+ let value = json!({
494
+ "ok": true,
495
+ "path": paths.store(),
496
+ "token": session.token,
497
+ "expiresAt": session.expires_at(),
498
+ "items": 0,
499
+ });
500
+ out.value(value, || format!("created {}", paths.store().display()));
501
+ Ok(())
502
+ }
503
+
504
+ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_ms: i64) -> Outcome {
505
+ let store = open_store(paths)?;
506
+ let password = if password_stdin {
507
+ read_password()?
508
+ } else {
509
+ ask_password("ai-vault · 解锁", "本地库主密码")?
510
+ };
511
+ let (items, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
512
+ crypto::OpenError::WrongPassword => {
513
+ audit::append(&paths.audit(), requester, "unlock_failed", None, Some("bad-password"));
514
+ Fault::Auth("wrong master password".into())
515
+ }
516
+ crypto::OpenError::Broken(message) => Fault::Error(message),
517
+ })?;
518
+ session::ensure_session_dir(paths)?;
519
+ session::sweep(paths);
520
+ let session = Session::new(requester, idle_ms, &store, &key);
521
+ session.save(paths)?;
522
+ audit::append(&paths.audit(), requester, "unlock", None, None);
523
+ let value = json!({
524
+ "ok": true,
525
+ "token": session.token,
526
+ "expiresAt": session.expires_at(),
527
+ "items": items.len(),
528
+ "requester": requester,
529
+ "path": paths.store(),
530
+ });
531
+ out.value(value, || format!("unlocked {} ({} entries)", paths.store().display(), items.len()));
532
+ Ok(())
533
+ }
534
+
535
+ fn status(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
536
+ let mut session = load_session(paths, token.as_deref())?;
537
+ let store = open_store(paths)?;
538
+ let items = items_with(&session, &store)?;
539
+ let now = session::now_ms();
540
+ session.prune_grants(now);
541
+ session.last_active = now;
542
+ session.save(paths)?;
543
+ let grants: serde_json::Map<String, serde_json::Value> = session
544
+ .grants
545
+ .iter()
546
+ .map(|(name, until)| (name.clone(), json!({ "expiresAt": until, "leftMs": until - now })))
547
+ .collect();
548
+ let value = json!({
549
+ "ok": true,
550
+ "unlocked": true,
551
+ "items": items.len(),
552
+ "requester": session.requester,
553
+ "idleMs": session.idle_ms,
554
+ "expiresAt": session.expires_at(),
555
+ "store": paths.store(),
556
+ "grants": grants,
557
+ });
558
+ out.value(value.clone(), || {
559
+ let mut lines = vec![
560
+ format!("store: {}", paths.store().display()),
561
+ format!("requester: {}", session.requester),
562
+ "state: unlocked".to_string(),
563
+ format!("items: {}", items.len()),
564
+ format!("expires: in {}s", ((session.expires_at() - now) / 1000).max(0)),
565
+ ];
566
+ for (name, until) in &session.grants {
567
+ lines.push(format!("grant: {name} ({}s left)", ((until - now) / 1000).max(0)));
568
+ }
569
+ lines.join("\n")
570
+ });
571
+ Ok(())
572
+ }
573
+
574
+ fn lock(paths: &Paths, out: &Out, token: Option<String>, all: bool) -> Outcome {
575
+ let mut count = 0;
576
+ if all {
577
+ count = session::delete_all(paths);
578
+ } else if let Some(token) = token.filter(|t| !t.is_empty()) {
579
+ if session::delete(paths, &token) {
580
+ count = 1;
581
+ }
582
+ } else {
583
+ return Err(Fault::Usage("pass --token or --all".into()));
584
+ }
585
+ audit::append(&paths.audit(), "cli", "lock", None, Some(if all { "all" } else { "token" }));
586
+ out.value(json!({ "ok": true, "removed": count }), || format!("locked {count} session(s)"));
587
+ Ok(())
588
+ }
589
+
590
+ fn list(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
591
+ let mut session = load_session(paths, token.as_deref())?;
592
+ let store = open_store(paths)?;
593
+ let items = items_with(&session, &store)?;
594
+ let summaries: Vec<ItemSummary> = items.iter().map(ItemSummary::from).collect();
595
+ touch(paths, &mut session);
596
+ audit::append(&paths.audit(), &session.requester, "list", None, None);
597
+ out.value(json!({ "ok": true, "count": summaries.len(), "items": summaries }), || {
598
+ if items.is_empty() {
599
+ return "(empty)".to_string();
600
+ }
601
+ items
602
+ .iter()
603
+ .map(|i| format!("{}\t{}\t{}", i.name, i.username.clone().unwrap_or_default(), i.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default()))
604
+ .collect::<Vec<_>>()
605
+ .join("\n")
606
+ });
607
+ Ok(())
608
+ }
609
+
610
+ fn get(
611
+ paths: &Paths,
612
+ out: &Out,
613
+ token: Option<String>,
614
+ name: &str,
615
+ reason: Option<&str>,
616
+ answer_stdin: bool,
617
+ ) -> Outcome {
618
+ let mut session = load_session(paths, token.as_deref())?;
619
+ let store = open_store(paths)?;
620
+ let items = items_with(&session, &store)?;
621
+ let item = store::find(&items, name).cloned().ok_or_else(|| {
622
+ let names = items.iter().map(|i| i.name.clone()).collect::<Vec<_>>().join(", ");
623
+ Fault::Error(format!("no such entry: \"{name}\". available: {}", if names.is_empty() { "(empty)" } else { &names }))
624
+ })?;
625
+
626
+ let now = session::now_ms();
627
+ let via = if session.grant(&item.name, now).is_some() {
628
+ "existing-grant"
629
+ } else {
630
+ let message = format!(
631
+ "条目: {}\n请求方: {}\n原因: {}\n\n允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
632
+ item.name,
633
+ session.requester,
634
+ reason.unwrap_or("(未说明)")
635
+ );
636
+ let approved = if answer_stdin {
637
+ read_approval()?
638
+ } else {
639
+ match dialog::confirm("ai-vault · 读取本地密码", &message) {
640
+ Answer::Value(ok) => ok,
641
+ Answer::Cancelled => false,
642
+ Answer::NoUi => {
643
+ audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), Some("no-ui"));
644
+ return Err(Fault::NeedsUi("confirm"));
645
+ }
646
+ }
647
+ };
648
+ if !approved {
649
+ audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), reason);
650
+ return Err(Fault::Denied(format!("user denied access to \"{}\" — do not retry, ask the user instead", item.name)));
651
+ }
652
+ // The window may have outlived the idle lock or overlapped a write.
653
+ session = load_session(paths, token.as_deref())?;
654
+ let store = open_store(paths)?;
655
+ let items = items_with(&session, &store)?;
656
+ if store::find(&items, &item.name).is_none() {
657
+ return Err(Fault::Error(format!("\"{}\" was removed while the window was open", item.name)));
658
+ }
659
+ session.grants.insert(item.name.to_lowercase(), session::now_ms() + GRANT_MS_DEFAULT);
660
+ audit::append(&paths.audit(), &session.requester, "grant", Some(&item.name), Some("interactive"));
661
+ "interactive-grant"
662
+ };
663
+
664
+ session.last_active = session::now_ms();
665
+ session.save(paths)?;
666
+ audit::append(&paths.audit(), &session.requester, "read_allow", Some(&item.name), reason);
667
+
668
+ let mut value = serde_json::to_value(&item).map_err(|e| Fault::Error(e.to_string()))?;
669
+ if let Some(record) = value.as_object_mut() {
670
+ record.insert("via".into(), json!(via));
671
+ }
672
+ out.value(value.clone(), || serde_json::to_string_pretty(&value).unwrap_or_default());
673
+ Ok(())
674
+ }
675
+
676
+ struct AddRequest {
677
+ name: String,
678
+ username: Option<String>,
679
+ uri: Option<String>,
680
+ notes: Option<String>,
681
+ password_stdin: bool,
682
+ yes: bool,
683
+ }
684
+
685
+ fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outcome {
686
+ let mut session = load_session(paths, token.as_deref())?;
687
+ let name = req.name.trim().to_string();
688
+ if name.is_empty() {
689
+ return Err(Fault::Usage("an entry needs a name".into()));
690
+ }
691
+ let store = open_store(paths)?;
692
+ let items = items_with(&session, &store)?;
693
+ let existing = store::find(&items, &name).cloned();
694
+
695
+ if !req.yes {
696
+ let mut meta = Vec::new();
697
+ if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
698
+ meta.push(format!("用户名: {user}"));
699
+ }
700
+ if let Some(uri) = req.uri.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
701
+ meta.push(format!("URI: {uri}"));
702
+ }
703
+ if let Some(notes) = req.notes.as_deref().map(str::trim).filter(|n| !n.is_empty()) {
704
+ meta.push(format!("备注: {notes}"));
705
+ }
706
+ let action = if existing.is_some() {
707
+ format!("更新已有条目「{name}」。")
708
+ } else {
709
+ format!("新建条目「{name}」。")
710
+ };
711
+ let message = format!(
712
+ "{action}{}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。",
713
+ if meta.is_empty() { String::new() } else { format!("\n{}", meta.join("\n")) }
714
+ );
715
+ match dialog::confirm("ai-vault · 保存到本地库", &message) {
716
+ Answer::Value(true) => {}
717
+ Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied(format!("user denied saving \"{name}\""))),
718
+ Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
719
+ }
720
+ }
721
+
722
+ let username = match req.username {
723
+ Some(user) => user,
724
+ None => {
725
+ let hint = if existing.as_ref().and_then(|i| i.username.as_ref()).is_some() {
726
+ "用户名(留空保持不变)"
727
+ } else {
728
+ "用户名(可留空)"
729
+ };
730
+ ask_text(&format!("ai-vault · {name}"), hint)?
731
+ }
732
+ };
733
+ let password = if req.password_stdin {
734
+ read_password()?
735
+ } else {
736
+ ask_password("ai-vault · 密码", &name)?
737
+ };
738
+ if password.is_empty() {
739
+ return Err(Fault::Denied("cancelled: no password entered".into()));
740
+ }
741
+
742
+ let user = username.trim().to_string();
743
+ let uri = req.uri.map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
744
+ let notes = req.notes.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
745
+ let draft = Draft {
746
+ id: None,
747
+ name: name.clone(),
748
+ username: if user.is_empty() { None } else { Some(user) },
749
+ password,
750
+ uris: uri.map(|u| vec![u]),
751
+ notes,
752
+ source: None,
753
+ };
754
+ let mut inserted = false;
755
+ mutate(paths, &session, |items, now| {
756
+ inserted = store::apply(items, draft, now);
757
+ Ok(())
758
+ })?;
759
+ session.last_active = session::now_ms();
760
+ session.save(paths)?;
761
+ audit::append(&paths.audit(), &session.requester, "add", Some(&name), None);
762
+ out.value(json!({ "ok": true, "item": name, "created": inserted }), || {
763
+ format!("saved \"{name}\" (password entered in the dialog, not shown)")
764
+ });
765
+ Ok(())
766
+ }
767
+
768
+ fn save(paths: &Paths, out: &Out, token: Option<String>, file: Option<PathBuf>, yes: bool) -> Outcome {
769
+ if !yes {
770
+ return Err(Fault::Usage("save needs --yes: the caller must confirm the write with the user".into()));
771
+ }
772
+ let mut session = load_session(paths, token.as_deref())?;
773
+ let text = match file {
774
+ Some(path) => std::fs::read_to_string(&path)
775
+ .map_err(|e| Fault::Error(format!("cannot read {}: {e}", path.display())))?,
776
+ None => read_stdin_text()?,
777
+ };
778
+ let drafts = import::parse_drafts(&text)?;
779
+ if drafts.is_empty() {
780
+ out.value(json!({ "ok": true, "count": 0, "names": [] }), || "nothing to save".to_string());
781
+ return Ok(());
782
+ }
783
+ let names: Vec<String> = drafts.iter().map(|d| d.name.clone()).collect();
784
+ let mut count = 0;
785
+ mutate(paths, &session, |items, now| {
786
+ for draft in drafts {
787
+ store::apply(items, draft, now);
788
+ count += 1;
789
+ }
790
+ Ok(())
791
+ })?;
792
+ session.last_active = session::now_ms();
793
+ session.save(paths)?;
794
+ audit::append(&paths.audit(), &session.requester, "import", Some(&format!("drafts:{count}")), None);
795
+ out.value(json!({ "ok": true, "count": count, "names": names }), || format!("saved {count} entries"));
796
+ Ok(())
797
+ }
798
+
799
+ fn remove(paths: &Paths, out: &Out, token: Option<String>, name: &str, yes: bool) -> Outcome {
800
+ let mut session = load_session(paths, token.as_deref())?;
801
+ let store = open_store(paths)?;
802
+ let items = items_with(&session, &store)?;
803
+ if store::find(&items, name).is_none() {
804
+ return Err(Fault::Error(format!("no such entry: \"{name}\"")));
805
+ }
806
+ if !yes {
807
+ match dialog::confirm("ai-vault · 删除条目", &format!("删除「{name}」?删除后无法恢复。")) {
808
+ Answer::Value(true) => {}
809
+ Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
810
+ Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
811
+ }
812
+ }
813
+ let mut removed = false;
814
+ mutate(paths, &session, |items, _now| {
815
+ removed = store::remove(items, name);
816
+ Ok(())
817
+ })?;
818
+ session.grants.remove(&name.to_lowercase());
819
+ session.last_active = session::now_ms();
820
+ session.save(paths)?;
821
+ audit::append(&paths.audit(), &session.requester, "remove", Some(name), None);
822
+ out.value(json!({ "ok": true, "removed": removed }), || if removed { "removed".to_string() } else { "not found".to_string() });
823
+ Ok(())
824
+ }
825
+
826
+ fn grant(paths: &Paths, out: &Out, token: Option<String>, name: &str, minutes: Option<i64>) -> Outcome {
827
+ let mut session = load_session(paths, token.as_deref())?;
828
+ let store = open_store(paths)?;
829
+ let items = items_with(&session, &store)?;
830
+ let item = store::find(&items, name).ok_or_else(|| Fault::Error(format!("no such entry: \"{name}\"")))?;
831
+ let minutes = minutes.unwrap_or(GRANT_MS_DEFAULT / 60_000).clamp(1, GRANT_MS_MAX / 60_000);
832
+ let until = session::now_ms() + minutes * 60_000;
833
+ session.grants.insert(item.name.to_lowercase(), until);
834
+ session.last_active = session::now_ms();
835
+ session.save(paths)?;
836
+ audit::append(&paths.audit(), &session.requester, "grant", Some(&item.name), Some("manual"));
837
+ out.value(json!({ "ok": true, "name": item.name, "minutes": minutes, "expiresAt": until }), || {
838
+ format!("granted \"{}\" for {minutes}m", item.name)
839
+ });
840
+ Ok(())
841
+ }
842
+
843
+ fn revoke(paths: &Paths, out: &Out, token: Option<String>, name: Option<&str>, all: bool) -> Outcome {
844
+ let mut session = load_session(paths, token.as_deref())?;
845
+ if all {
846
+ session.grants.clear();
847
+ } else if let Some(name) = name.filter(|n| !n.is_empty()) {
848
+ session.grants.remove(&name.to_lowercase());
849
+ } else {
850
+ return Err(Fault::Usage("pass an entry name or --all".into()));
851
+ }
852
+ session.last_active = session::now_ms();
853
+ session.save(paths)?;
854
+ audit::append(&paths.audit(), &session.requester, "revoke", name, Some(if all { "all" } else { "entry" }));
855
+ out.value(json!({ "ok": true }), || "revoked".to_string());
856
+ Ok(())
857
+ }
858
+
859
+ fn audit_entries(paths: &Paths, out: &Out, n: usize) -> Outcome {
860
+ let limit = n.clamp(1, 1000);
861
+ let entries = audit::read(&paths.audit(), limit);
862
+ out.value(json!({ "ok": true, "entries": entries }), || {
863
+ entries
864
+ .iter()
865
+ .map(|e| {
866
+ format!(
867
+ "{} {} {}{}{}",
868
+ e.ts,
869
+ e.session,
870
+ e.event,
871
+ e.item.as_ref().map(|i| format!(" {i}")).unwrap_or_default(),
872
+ e.reason.as_ref().map(|r| format!(" ({r})")).unwrap_or_default()
873
+ )
874
+ })
875
+ .collect::<Vec<_>>()
876
+ .join("\n")
877
+ });
878
+ Ok(())
879
+ }
880
+
881
+ fn import_file(paths: &Paths, out: &Out, token: Option<String>, file: &PathBuf, yes: bool) -> Outcome {
882
+ let mut session = load_session(paths, token.as_deref())?;
883
+ let text = std::fs::read_to_string(file)
884
+ .map_err(|e| Fault::Error(format!("cannot read {}: {e}", file.display())))?;
885
+ let drafts = import::parse_bitwarden_json(&text)?;
886
+ if drafts.is_empty() {
887
+ return Err(Fault::Error("no login items with a password in that export".into()));
888
+ }
889
+ if !yes {
890
+ let shown = drafts
891
+ .iter()
892
+ .take(15)
893
+ .map(|d| format!("• {}{}", d.name, d.username.as_ref().map(|u| format!(" user:{u}")).unwrap_or_default()))
894
+ .collect::<Vec<_>>()
895
+ .join("\n");
896
+ let more = if drafts.len() > 15 { format!("\n… 还有 {} 条", drafts.len() - 15) } else { String::new() };
897
+ let message = format!(
898
+ "匹配 {} 条。其中带密码的登录项会写入本地加密库,同名条目会被更新。\n\n{shown}{more}\n\n允许导入?",
899
+ drafts.len()
900
+ );
901
+ match dialog::confirm("ai-vault · 从 Bitwarden 导入", &message) {
902
+ Answer::Value(true) => {}
903
+ Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("user denied the Bitwarden import".into())),
904
+ Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
905
+ }
906
+ }
907
+ let names: Vec<String> = drafts.iter().map(|d| d.name.clone()).collect();
908
+ let mut count = 0;
909
+ mutate(paths, &session, |items, now| {
910
+ for draft in drafts {
911
+ store::apply(items, draft, now);
912
+ count += 1;
913
+ }
914
+ Ok(())
915
+ })?;
916
+ session.last_active = session::now_ms();
917
+ session.save(paths)?;
918
+ audit::append(&paths.audit(), &session.requester, "import", Some(&format!("json:{count}")), None);
919
+ out.value(json!({ "ok": true, "count": count, "names": names }), || format!("imported {count} login items"));
920
+ Ok(())
921
+ }
922
+
923
+ #[cfg(test)]
924
+ mod tests {
925
+ use super::*;
926
+
927
+ #[test]
928
+ fn exit_codes_are_stable() {
929
+ assert_eq!(Fault::Error("x".into()).exit_code(), 1);
930
+ assert_eq!(Fault::Usage("x".into()).exit_code(), 2);
931
+ assert_eq!(Fault::NeedsUi("password").exit_code(), 3);
932
+ assert_eq!(Fault::Denied("x".into()).exit_code(), 4);
933
+ assert_eq!(Fault::Auth("x".into()).exit_code(), 5);
934
+ }
935
+
936
+ #[test]
937
+ fn idle_is_clamped() {
938
+ assert_eq!(idle_ms(None), IDLE_MS_DEFAULT);
939
+ assert_eq!(idle_ms(Some(0)), 60_000);
940
+ assert_eq!(idle_ms(Some(1000)), 600 * 60_000);
941
+ }
942
+ }