@xiaolikt/ai-vault 0.5.0 → 0.7.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.
- package/Cargo.lock +2 -1
- package/README.md +73 -11
- package/crates/ai-vault/Cargo.toml +2 -1
- package/crates/ai-vault/src/bwsession.rs +163 -0
- package/crates/ai-vault/src/cli.rs +380 -75
- package/crates/ai-vault/src/config.rs +99 -5
- package/crates/ai-vault/src/crypto.rs +34 -8
- package/crates/ai-vault/src/dialog.rs +45 -0
- package/crates/ai-vault/src/main.rs +1 -0
- package/crates/ai-vault/src/paths.rs +12 -0
- package/crates/ai-vault/src/session.rs +82 -13
- package/package.json +2 -2
- package/packages/pi-ai-vault/README.md +13 -1
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +30 -0
- package/packages/pi-ai-vault/src/cli.ts +58 -1
- package/packages/pi-ai-vault/src/index.ts +111 -54
- package/packages/pi-ai-vault/src/prompt.ts +13 -0
- package/packages/pi-ai-vault/src/settings.ts +59 -0
- package/test/cli.sh +106 -5
- package/tests/prompt.test.mjs +12 -0
- package/tests/vault-cli.test.mjs +98 -0
|
@@ -9,7 +9,8 @@ use std::path::PathBuf;
|
|
|
9
9
|
use clap::{Parser, Subcommand};
|
|
10
10
|
use serde_json::json;
|
|
11
11
|
|
|
12
|
-
use crate::
|
|
12
|
+
use crate::bwsession;
|
|
13
|
+
use crate::config::{self, ImportPolicy, UnlockMode, UnlockPolicy};
|
|
13
14
|
use crate::crypto::{self, Kdf};
|
|
14
15
|
use crate::dialog::{self, Answer};
|
|
15
16
|
use crate::import;
|
|
@@ -67,6 +68,22 @@ enum Cmd {
|
|
|
67
68
|
#[arg(long, value_name = "MIN")]
|
|
68
69
|
idle_min: Option<i64>,
|
|
69
70
|
},
|
|
71
|
+
/// Show or change machine-wide settings
|
|
72
|
+
Settings {
|
|
73
|
+
/// Dotted key (vault.unlock, vault.hours, bitwarden.unlock,
|
|
74
|
+
/// bitwarden.hours, bitwarden.import); omit to print everything
|
|
75
|
+
key: Option<String>,
|
|
76
|
+
/// New value; omit to print the current one
|
|
77
|
+
value: Option<String>,
|
|
78
|
+
/// Read the vault master password from stdin (changing vault.unlock)
|
|
79
|
+
#[arg(long)]
|
|
80
|
+
password_stdin: bool,
|
|
81
|
+
},
|
|
82
|
+
/// The persisted `bw` session key (bitwarden.unlock = never | time)
|
|
83
|
+
BwSession {
|
|
84
|
+
/// get | put | clear
|
|
85
|
+
action: String,
|
|
86
|
+
},
|
|
70
87
|
/// Show or change how often the master password is asked for
|
|
71
88
|
Mode {
|
|
72
89
|
/// "get" or "set"
|
|
@@ -106,9 +123,14 @@ enum Cmd {
|
|
|
106
123
|
/// Why the secret is needed (shown in the confirm window)
|
|
107
124
|
#[arg(long)]
|
|
108
125
|
reason: Option<String>,
|
|
109
|
-
/// Read the approve/deny answer from stdin (host UI already asked)
|
|
126
|
+
/// Read the approve/deny answer from stdin (host UI already asked).
|
|
127
|
+
/// Requires AI_VAULT_HOST=1 and a matching --approval.
|
|
110
128
|
#[arg(long)]
|
|
111
129
|
answer_stdin: bool,
|
|
130
|
+
/// HMAC-SHA256(hex) of "allow:<token>:<entry>:y|n" under the host
|
|
131
|
+
/// secret, proving a host that holds the secret relayed the answer.
|
|
132
|
+
#[arg(long, value_name = "HEX")]
|
|
133
|
+
approval: Option<String>,
|
|
112
134
|
},
|
|
113
135
|
/// Create or update an entry; the password is typed in a dialog
|
|
114
136
|
Add {
|
|
@@ -176,6 +198,11 @@ enum Cmd {
|
|
|
176
198
|
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
177
199
|
token: Option<String>,
|
|
178
200
|
},
|
|
201
|
+
/// Re-encrypt the store under the current default KDF (asks the master password)
|
|
202
|
+
Rekey {
|
|
203
|
+
#[arg(long)]
|
|
204
|
+
password_stdin: bool,
|
|
205
|
+
},
|
|
179
206
|
/// Diagnose paths, session directory and desktop availability
|
|
180
207
|
Doctor,
|
|
181
208
|
}
|
|
@@ -220,6 +247,11 @@ pub fn run() -> i32 {
|
|
|
220
247
|
};
|
|
221
248
|
let paths = Paths::resolve(cli.dir.clone());
|
|
222
249
|
migrate_legacy(&paths);
|
|
250
|
+
// Dead token files (expired, unsigned, from an older store) carry keys
|
|
251
|
+
// that open nothing; drop them on sight rather than after a week.
|
|
252
|
+
if paths.sessions().is_dir() {
|
|
253
|
+
session::sweep(&paths);
|
|
254
|
+
}
|
|
223
255
|
let json = cli.json;
|
|
224
256
|
match dispatch(cli.cmd, &paths, json) {
|
|
225
257
|
Ok(()) => 0,
|
|
@@ -278,6 +310,7 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
|
|
|
278
310
|
out.text(paths.store().display().to_string());
|
|
279
311
|
Ok(())
|
|
280
312
|
}
|
|
313
|
+
Cmd::Rekey { password_stdin } => rekey(paths, &out, password_stdin),
|
|
281
314
|
Cmd::Doctor => doctor(paths, &out),
|
|
282
315
|
Cmd::Init { password_stdin, requester, idle_min } => {
|
|
283
316
|
init(paths, &out, password_stdin, &requester, idle_min)
|
|
@@ -285,14 +318,18 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
|
|
|
285
318
|
Cmd::Unlock { password_stdin, requester, idle_min } => {
|
|
286
319
|
unlock(paths, &out, password_stdin, &requester, idle_min)
|
|
287
320
|
}
|
|
321
|
+
Cmd::Settings { key, value, password_stdin } => {
|
|
322
|
+
settings(paths, &out, key.as_deref(), value.as_deref(), None, password_stdin)
|
|
323
|
+
}
|
|
324
|
+
Cmd::BwSession { action } => bw_session(paths, &out, &action),
|
|
288
325
|
Cmd::Mode { action, value, hours, password_stdin } => {
|
|
289
326
|
mode(paths, &out, &action, value.as_deref(), hours, password_stdin)
|
|
290
327
|
}
|
|
291
328
|
Cmd::Status { token } => status(paths, &out, token),
|
|
292
329
|
Cmd::Lock { token, all } => lock(paths, &out, token, all),
|
|
293
330
|
Cmd::List { token } => list(paths, &out, token),
|
|
294
|
-
Cmd::Get { name, token, reason, answer_stdin } => {
|
|
295
|
-
get(paths, &out, token, &name, reason.as_deref(), answer_stdin)
|
|
331
|
+
Cmd::Get { name, token, reason, answer_stdin, approval } => {
|
|
332
|
+
get(paths, &out, token, &name, reason.as_deref(), answer_stdin, approval)
|
|
296
333
|
}
|
|
297
334
|
Cmd::Add { name, username, uri, notes, password_stdin, yes, token } => {
|
|
298
335
|
add(paths, &out, token, AddRequest { name, username, uri, notes, password_stdin, yes })
|
|
@@ -384,6 +421,21 @@ fn read_stdin_text() -> Result<String, Fault> {
|
|
|
384
421
|
}
|
|
385
422
|
|
|
386
423
|
/// A yes/no answer from stdin, used when the host UI already asked the user.
|
|
424
|
+
/// The answer a host relays is bound to this token, this entry and this
|
|
425
|
+
/// yes/no, under the host secret: a replay against another entry, or a
|
|
426
|
+
/// flipped answer, fails.
|
|
427
|
+
fn approval_ok(secret: &str, token: &str, entry: &str, answer: bool, hex_mac: &str) -> bool {
|
|
428
|
+
use hmac::{Hmac, Mac};
|
|
429
|
+
let message = format!("allow:{token}:{}:{}", entry.to_lowercase(), if answer { "y" } else { "n" });
|
|
430
|
+
let Ok(mut hasher) = <Hmac<sha2::Sha256> as Mac>::new_from_slice(secret.as_bytes()) else {
|
|
431
|
+
return false;
|
|
432
|
+
};
|
|
433
|
+
hasher.update(message.as_bytes());
|
|
434
|
+
let expected: String = hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
|
|
435
|
+
expected.len() == hex_mac.len()
|
|
436
|
+
&& expected.bytes().zip(hex_mac.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0
|
|
437
|
+
}
|
|
438
|
+
|
|
387
439
|
fn read_approval() -> Result<bool, Fault> {
|
|
388
440
|
let answer = read_line()?.trim().to_lowercase();
|
|
389
441
|
Ok(matches!(answer.as_str(), "y" | "yes" | "allow" | "允许" | "1" | "true"))
|
|
@@ -423,6 +475,31 @@ fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>,
|
|
|
423
475
|
})
|
|
424
476
|
}
|
|
425
477
|
|
|
478
|
+
/// The secret the host process (pi/omp extension) holds and passes to each
|
|
479
|
+
/// CLI call through the environment. A bare `ai-vault` typed by a human has
|
|
480
|
+
/// none, which is fine: that caller never needs to relay an approval.
|
|
481
|
+
fn host_secret() -> Option<String> {
|
|
482
|
+
std::env::var("AI_VAULT_HOST_SECRET").ok().filter(|s| !s.is_empty())
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/// What session files are signed with: the host's memory-only secret when
|
|
486
|
+
/// there is one, else the store's wrap key (a human at a terminal).
|
|
487
|
+
fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
|
|
488
|
+
if let Some(secret) = host_secret() {
|
|
489
|
+
return Ok(Some(secret));
|
|
490
|
+
}
|
|
491
|
+
bwsession::wrap_key_hex(paths).map(Some)
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/// The host integration (the extension) is recognised by the secret it
|
|
495
|
+
/// presents: `AI_VAULT_HOST=1` alone only says "I would like to be a host"
|
|
496
|
+
/// and is treated like a human caller until it has a secret to sign with.
|
|
497
|
+
/// This keeps a half-configured host from getting a session it can neither
|
|
498
|
+
/// verify nor relay for.
|
|
499
|
+
fn is_host() -> bool {
|
|
500
|
+
std::env::var_os("AI_VAULT_HOST").is_some_and(|v| v == "1") && host_secret().is_some()
|
|
501
|
+
}
|
|
502
|
+
|
|
426
503
|
/// The auto session is the `never` mode token: no deadline, no password, and
|
|
427
504
|
/// it belongs to the machine rather than to one agent.
|
|
428
505
|
fn auto_session(paths: &Paths) -> Option<Session> {
|
|
@@ -438,7 +515,7 @@ fn auto_session(paths: &Paths) -> Option<Session> {
|
|
|
438
515
|
/// An explicit token, else the machine-wide auto session.
|
|
439
516
|
fn load_session(paths: &Paths, token: Option<&str>) -> Result<Session, Fault> {
|
|
440
517
|
if let Some(token) = token.filter(|t| !t.is_empty()) {
|
|
441
|
-
return session::load(paths, token).map_err(Fault::Auth);
|
|
518
|
+
return session::load(paths, token, signing_key(paths)?.as_deref()).map_err(Fault::Auth);
|
|
442
519
|
}
|
|
443
520
|
auto_session(paths).ok_or_else(|| {
|
|
444
521
|
Fault::Auth("vault is locked (no session token) — unlock first".into())
|
|
@@ -452,7 +529,16 @@ fn persist(paths: &Paths, session: &Session) {
|
|
|
452
529
|
.ok()
|
|
453
530
|
.flatten()
|
|
454
531
|
.is_some_and(|saved| saved.token == session.token);
|
|
455
|
-
let _ = if auto {
|
|
532
|
+
let _ = if auto {
|
|
533
|
+
session::save_auto(paths, session)
|
|
534
|
+
} else {
|
|
535
|
+
// Best-effort like the rest of this helper; a failed sign means the
|
|
536
|
+
// next call simply asks to unlock again.
|
|
537
|
+
match signing_key(paths) {
|
|
538
|
+
Ok(key) => session.save(paths, key.as_deref()),
|
|
539
|
+
Err(e) => Err(e),
|
|
540
|
+
}
|
|
541
|
+
};
|
|
456
542
|
}
|
|
457
543
|
|
|
458
544
|
fn touch(paths: &Paths, session: &mut Session) {
|
|
@@ -484,6 +570,42 @@ where
|
|
|
484
570
|
|
|
485
571
|
// ---------------------------------------------------------------- commands
|
|
486
572
|
|
|
573
|
+
/// Bring an older store up to the current KDF cost. Re-derives the key from
|
|
574
|
+
/// the password under the new parameters and re-seals; a `never`-mode
|
|
575
|
+
/// machine session, which holds the old key, is re-minted.
|
|
576
|
+
fn rekey(paths: &Paths, out: &Out, password_stdin: bool) -> Outcome {
|
|
577
|
+
let store = open_store(paths)?;
|
|
578
|
+
let password = if password_stdin {
|
|
579
|
+
read_password()?
|
|
580
|
+
} else {
|
|
581
|
+
ask_password("ai-vault · 升级密钥参数", "主密码")?
|
|
582
|
+
};
|
|
583
|
+
let (items, _old_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
584
|
+
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
585
|
+
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
586
|
+
})?;
|
|
587
|
+
let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| Fault::Error("vault salt is corrupt".into()))?;
|
|
588
|
+
let kdf = Kdf::default();
|
|
589
|
+
let new_key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
|
|
590
|
+
let sealed = crypto::seal(&salt, kdf, &new_key, &items)?;
|
|
591
|
+
{
|
|
592
|
+
let _guard = StoreLock::acquire(paths)?;
|
|
593
|
+
let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
|
|
594
|
+
crypto::write_atomic(&paths.store(), &bytes)?;
|
|
595
|
+
}
|
|
596
|
+
// Other live sessions hold the old key; they cannot open the new file and
|
|
597
|
+
// will be told to unlock again. The machine session is simply re-minted.
|
|
598
|
+
let _ = session::delete_auto(paths);
|
|
599
|
+
if config::load(paths).unlock.mode == UnlockMode::Never {
|
|
600
|
+
let auto = Session::new("rekey", 0, None, &sealed, &new_key);
|
|
601
|
+
session::save_auto(paths, &auto)?;
|
|
602
|
+
}
|
|
603
|
+
audit::append(&paths.audit(), "cli", "rekey", None, Some(&format!("N={}", kdf.n)));
|
|
604
|
+
let value = json!({ "ok": true, "kdf": { "N": kdf.n, "r": kdf.r, "p": kdf.p }, "was": { "N": store.kdf().n, "r": store.kdf().r, "p": store.kdf().p } });
|
|
605
|
+
out.value(value, || format!("rekeyed: scrypt N {} -> {}", store.kdf().n, kdf.n));
|
|
606
|
+
Ok(())
|
|
607
|
+
}
|
|
608
|
+
|
|
487
609
|
fn doctor(paths: &Paths, out: &Out) -> Outcome {
|
|
488
610
|
session::ensure_session_dir(paths)?;
|
|
489
611
|
let value = json!({
|
|
@@ -497,6 +619,7 @@ fn doctor(paths: &Paths, out: &Out) -> Outcome {
|
|
|
497
619
|
"zenity": which("zenity"),
|
|
498
620
|
"mode": config::load(paths).unlock.mode.as_str(),
|
|
499
621
|
"auto": paths.auto_session().exists(),
|
|
622
|
+
"kdf": crypto::read_store(&paths.store()).ok().flatten().map(|s| s.kdf().n),
|
|
500
623
|
});
|
|
501
624
|
out.value(value.clone(), || {
|
|
502
625
|
let mut lines = Vec::new();
|
|
@@ -552,17 +675,19 @@ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_mi
|
|
|
552
675
|
}
|
|
553
676
|
session::ensure_session_dir(paths)?;
|
|
554
677
|
let (idle, deadline, policy) = policy(paths, idle_min);
|
|
678
|
+
let secret = signing_key(paths)?;
|
|
555
679
|
let session = Session::new(requester, idle, deadline, &sealed, &key);
|
|
556
680
|
if policy.mode == UnlockMode::Never {
|
|
557
681
|
session::save_auto(paths, &session)?;
|
|
558
682
|
} else {
|
|
559
|
-
session.save(paths)?;
|
|
683
|
+
session.save(paths, secret.as_deref())?;
|
|
560
684
|
}
|
|
561
685
|
audit::append(&paths.audit(), requester, "init", None, None);
|
|
562
686
|
let value = json!({
|
|
563
687
|
"ok": true,
|
|
564
688
|
"path": paths.store(),
|
|
565
689
|
"token": session.token,
|
|
690
|
+
"hostSecret": if policy.mode == UnlockMode::Never || !is_host() { None } else { host_secret() },
|
|
566
691
|
"expiresAt": session.expiry(),
|
|
567
692
|
"items": 0,
|
|
568
693
|
"mode": policy.mode.as_str(),
|
|
@@ -589,16 +714,22 @@ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_
|
|
|
589
714
|
session::ensure_session_dir(paths)?;
|
|
590
715
|
session::sweep(paths);
|
|
591
716
|
let (idle, deadline, policy) = policy(paths, idle_min);
|
|
717
|
+
// A host that did not pass a secret gets a fresh one to keep for this
|
|
718
|
+
// session: it is the only thing that can sign later edits to the file.
|
|
719
|
+
// The host brings its own secret (so the same process can sign later
|
|
720
|
+
// calls); everyone else is signed with the wrap key.
|
|
721
|
+
let secret = signing_key(paths)?;
|
|
592
722
|
let session = Session::new(requester, idle, deadline, &store, &key);
|
|
593
723
|
if policy.mode == UnlockMode::Never {
|
|
594
724
|
session::save_auto(paths, &session)?;
|
|
595
725
|
} else {
|
|
596
|
-
session.save(paths)?;
|
|
726
|
+
session.save(paths, secret.as_deref())?;
|
|
597
727
|
}
|
|
598
728
|
audit::append(&paths.audit(), requester, "unlock", None, Some(policy.mode.as_str()));
|
|
599
729
|
let value = json!({
|
|
600
730
|
"ok": true,
|
|
601
731
|
"token": session.token,
|
|
732
|
+
"hostSecret": if policy.mode == UnlockMode::Never || !is_host() { None } else { host_secret() },
|
|
602
733
|
"expiresAt": session.expiry(),
|
|
603
734
|
"items": items.len(),
|
|
604
735
|
"requester": requester,
|
|
@@ -610,85 +741,214 @@ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_
|
|
|
610
741
|
Ok(())
|
|
611
742
|
}
|
|
612
743
|
|
|
613
|
-
///
|
|
614
|
-
|
|
615
|
-
|
|
744
|
+
/// Dotted setting names, with the aliases a human is likely to type.
|
|
745
|
+
fn setting_key(raw: &str) -> Option<&'static str> {
|
|
746
|
+
match raw.trim().to_lowercase().as_str() {
|
|
747
|
+
"vault.unlock" | "vault.mode" | "unlock" | "mode" => Some("vault.unlock"),
|
|
748
|
+
"vault.hours" | "hours" => Some("vault.hours"),
|
|
749
|
+
"bitwarden.unlock" | "bitwarden.mode" | "bw.unlock" | "bw.mode" => Some("bitwarden.unlock"),
|
|
750
|
+
"bitwarden.hours" | "bw.hours" => Some("bitwarden.hours"),
|
|
751
|
+
"bitwarden.import" | "bw.import" | "import" => Some("bitwarden.import"),
|
|
752
|
+
_ => None,
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
fn settings_value(config: &config::Config, paths: &Paths) -> serde_json::Value {
|
|
757
|
+
let bw_saved = bwsession::load(paths).ok().flatten();
|
|
758
|
+
json!({
|
|
759
|
+
"ok": true,
|
|
760
|
+
"vault": {
|
|
761
|
+
"unlock": config.unlock.mode.as_str(),
|
|
762
|
+
"hours": config.unlock.hours,
|
|
763
|
+
"auto": paths.auto_session().exists(),
|
|
764
|
+
},
|
|
765
|
+
"bitwarden": {
|
|
766
|
+
"unlock": config.bitwarden.unlock.as_str(),
|
|
767
|
+
"hours": config.bitwarden.hours,
|
|
768
|
+
"import": config.bitwarden.import.as_str(),
|
|
769
|
+
"persisted": bw_saved.is_some(),
|
|
770
|
+
"expiresAt": bw_saved.as_ref().and_then(|s| s.expires_at),
|
|
771
|
+
},
|
|
772
|
+
})
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
fn settings_human(config: &config::Config, paths: &Paths) -> String {
|
|
776
|
+
[
|
|
777
|
+
format!("vault.unlock: {} (never | time | session)", config.unlock.mode.as_str()),
|
|
778
|
+
format!("vault.hours: {} (time 模式)", config.unlock.hours),
|
|
779
|
+
format!(
|
|
780
|
+
"vault 机器级会话: {}",
|
|
781
|
+
if paths.auto_session().exists() { "有(免密)" } else { "无" }
|
|
782
|
+
),
|
|
783
|
+
format!("bitwarden.unlock: {} (never | time | session)", config.bitwarden.unlock.as_str()),
|
|
784
|
+
format!("bitwarden.hours: {}", config.bitwarden.hours),
|
|
785
|
+
format!("bitwarden.import: {} (ask | always | never)", config.bitwarden.import.as_str()),
|
|
786
|
+
format!(
|
|
787
|
+
"bitwarden 已落盘的会话: {}",
|
|
788
|
+
match bwsession::load(paths).ok().flatten() {
|
|
789
|
+
Some(saved) => match saved.expires_at {
|
|
790
|
+
Some(at) => format!("有({} 后过期)", ((at - session::now_ms()) / 60_000).max(0)),
|
|
791
|
+
None => "有(不过期)".to_string(),
|
|
792
|
+
},
|
|
793
|
+
None => "无".to_string(),
|
|
794
|
+
}
|
|
795
|
+
),
|
|
796
|
+
]
|
|
797
|
+
.join("\n")
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
fn settings(
|
|
616
801
|
paths: &Paths,
|
|
617
802
|
out: &Out,
|
|
618
|
-
|
|
803
|
+
key: Option<&str>,
|
|
619
804
|
value: Option<&str>,
|
|
620
805
|
hours: Option<i64>,
|
|
621
806
|
password_stdin: bool,
|
|
622
807
|
) -> Outcome {
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
let mode = UnlockMode::parse(
|
|
651
|
-
.ok_or_else(|| Fault::Usage(format!("unknown mode \"{
|
|
808
|
+
let mut config = config::load(paths);
|
|
809
|
+
|
|
810
|
+
let Some(raw_key) = key.filter(|k| !k.trim().is_empty()) else {
|
|
811
|
+
let value = settings_value(&config, paths);
|
|
812
|
+
out.value(value, || settings_human(&config, paths));
|
|
813
|
+
return Ok(());
|
|
814
|
+
};
|
|
815
|
+
let key = setting_key(raw_key).ok_or_else(|| {
|
|
816
|
+
Fault::Usage(format!(
|
|
817
|
+
"unknown setting \"{raw_key}\" — vault.unlock, vault.hours, bitwarden.unlock, bitwarden.hours, bitwarden.import"
|
|
818
|
+
))
|
|
819
|
+
})?;
|
|
820
|
+
|
|
821
|
+
let Some(raw_value) = value.map(str::trim).filter(|v| !v.is_empty()) else {
|
|
822
|
+
let shown = match key {
|
|
823
|
+
"vault.unlock" => config.unlock.mode.as_str().to_string(),
|
|
824
|
+
"vault.hours" => config.unlock.hours.to_string(),
|
|
825
|
+
"bitwarden.unlock" => config.bitwarden.unlock.as_str().to_string(),
|
|
826
|
+
"bitwarden.hours" => config.bitwarden.hours.to_string(),
|
|
827
|
+
_ => config.bitwarden.import.as_str().to_string(),
|
|
828
|
+
};
|
|
829
|
+
out.value(json!({ "ok": true, "key": key, "value": shown }), || format!("{key}: {shown}"));
|
|
830
|
+
return Ok(());
|
|
831
|
+
};
|
|
832
|
+
|
|
833
|
+
match key {
|
|
834
|
+
"vault.unlock" => {
|
|
835
|
+
let mode = UnlockMode::parse(raw_value)
|
|
836
|
+
.ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
|
|
652
837
|
let store = open_store(paths)?;
|
|
838
|
+
// Changing when the vault opens is a security decision: always verify.
|
|
653
839
|
let password = if password_stdin {
|
|
654
840
|
read_password()?
|
|
655
841
|
} else {
|
|
656
842
|
ask_password("ai-vault · 主密码", "切换解锁模式")?
|
|
657
843
|
};
|
|
658
|
-
let (_,
|
|
844
|
+
let (_, vault_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
659
845
|
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
660
846
|
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
661
847
|
})?;
|
|
662
|
-
|
|
663
|
-
config::save(paths, &config
|
|
848
|
+
config.unlock = UnlockPolicy { mode, hours: hours.unwrap_or(config.unlock.hours).clamp(1, 24 * 90) };
|
|
849
|
+
config::save(paths, &config)?;
|
|
664
850
|
session::ensure_session_dir(paths)?;
|
|
665
|
-
|
|
666
|
-
let
|
|
667
|
-
session::save_auto(paths, &
|
|
668
|
-
true
|
|
851
|
+
if mode == UnlockMode::Never {
|
|
852
|
+
let auto = Session::new("mode", 0, None, &store, &vault_key);
|
|
853
|
+
session::save_auto(paths, &auto)?;
|
|
669
854
|
} else {
|
|
670
855
|
session::delete_auto(paths);
|
|
671
|
-
|
|
672
|
-
};
|
|
856
|
+
}
|
|
673
857
|
audit::append(&paths.audit(), "cli", "mode", None, Some(mode.as_str()));
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
858
|
+
}
|
|
859
|
+
"vault.hours" => {
|
|
860
|
+
let hours: i64 = raw_value
|
|
861
|
+
.parse()
|
|
862
|
+
.map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
|
|
863
|
+
config.unlock.hours = hours.clamp(1, 24 * 90);
|
|
864
|
+
config::save(paths, &config)?;
|
|
865
|
+
}
|
|
866
|
+
"bitwarden.unlock" => {
|
|
867
|
+
let mode = UnlockMode::parse(raw_value)
|
|
868
|
+
.ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
|
|
869
|
+
config.bitwarden.unlock = mode;
|
|
870
|
+
if let Some(hours) = hours {
|
|
871
|
+
config.bitwarden.hours = hours.clamp(1, 24 * 90);
|
|
872
|
+
}
|
|
873
|
+
config::save(paths, &config)?;
|
|
874
|
+
// Going back to per-session must not leave a key on disk.
|
|
875
|
+
if mode == UnlockMode::Session {
|
|
876
|
+
bwsession::clear(paths);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
"bitwarden.hours" => {
|
|
880
|
+
let hours: i64 = raw_value
|
|
881
|
+
.parse()
|
|
882
|
+
.map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
|
|
883
|
+
config.bitwarden.hours = hours.clamp(1, 24 * 90);
|
|
884
|
+
config::save(paths, &config)?;
|
|
885
|
+
}
|
|
886
|
+
_ => {
|
|
887
|
+
let import = ImportPolicy::parse(raw_value).ok_or_else(|| {
|
|
888
|
+
Fault::Usage(format!("unknown import policy \"{raw_value}\" — ask, always or never"))
|
|
889
|
+
})?;
|
|
890
|
+
config.bitwarden.import = import;
|
|
891
|
+
config::save(paths, &config)?;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
let value = settings_value(&config, paths);
|
|
896
|
+
out.value(value, || settings_human(&config, paths));
|
|
897
|
+
Ok(())
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/// `/vault mode` is a shortcut for the `vault.unlock` setting.
|
|
901
|
+
fn mode(
|
|
902
|
+
paths: &Paths,
|
|
903
|
+
out: &Out,
|
|
904
|
+
action: &str,
|
|
905
|
+
value: Option<&str>,
|
|
906
|
+
hours: Option<i64>,
|
|
907
|
+
password_stdin: bool,
|
|
908
|
+
) -> Outcome {
|
|
909
|
+
match action.trim() {
|
|
910
|
+
"" | "get" | "status" => settings(paths, out, Some("vault.unlock"), None, None, password_stdin),
|
|
911
|
+
"set" => settings(paths, out, Some("vault.unlock"), value, hours, password_stdin),
|
|
912
|
+
other => Err(Fault::Usage(format!("unknown mode action \"{other}\""))),
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
fn bw_session(paths: &Paths, out: &Out, action: &str) -> Outcome {
|
|
917
|
+
match action.trim() {
|
|
918
|
+
"" | "get" => {
|
|
919
|
+
let stored = bwsession::load(paths)?
|
|
920
|
+
.ok_or_else(|| Fault::Auth("no persisted Bitwarden session — unlock Bitwarden first".into()))?;
|
|
921
|
+
let key = bwsession::key(paths)?.ok_or_else(|| Fault::Auth("no persisted Bitwarden session".into()))?;
|
|
679
922
|
out.value(
|
|
680
|
-
json!({ "ok": true, "
|
|
681
|
-
||
|
|
682
|
-
format!(
|
|
683
|
-
"mode set to {}{}",
|
|
684
|
-
mode.as_str(),
|
|
685
|
-
if auto { " — no password needed from now on" } else { "" }
|
|
686
|
-
) + warn
|
|
687
|
-
},
|
|
923
|
+
json!({ "ok": true, "key": key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
|
|
924
|
+
|| key,
|
|
688
925
|
);
|
|
689
926
|
Ok(())
|
|
690
927
|
}
|
|
691
|
-
|
|
928
|
+
"put" | "save" => {
|
|
929
|
+
let key = read_stdin_text()?.trim().to_string();
|
|
930
|
+
if key.is_empty() {
|
|
931
|
+
return Err(Fault::Usage("bw-session put expects the session key on stdin".into()));
|
|
932
|
+
}
|
|
933
|
+
let expires_at = bwsession::save(paths, &key)?;
|
|
934
|
+
audit::append(&paths.audit(), "cli", "bw_session", None, Some("put"));
|
|
935
|
+
out.value(json!({ "ok": true, "expiresAt": expires_at }), || {
|
|
936
|
+
match expires_at {
|
|
937
|
+
Some(at) => format!("saved (expires in {} min)", ((at - session::now_ms()) / 60_000).max(0)),
|
|
938
|
+
None => "saved (no expiry)".to_string(),
|
|
939
|
+
}
|
|
940
|
+
});
|
|
941
|
+
Ok(())
|
|
942
|
+
}
|
|
943
|
+
"clear" | "delete" => {
|
|
944
|
+
let removed = bwsession::clear(paths);
|
|
945
|
+
audit::append(&paths.audit(), "cli", "bw_session", None, Some("clear"));
|
|
946
|
+
out.value(json!({ "ok": true, "removed": removed }), || {
|
|
947
|
+
if removed { "cleared".to_string() } else { "nothing stored".to_string() }
|
|
948
|
+
});
|
|
949
|
+
Ok(())
|
|
950
|
+
}
|
|
951
|
+
other => Err(Fault::Usage(format!("unknown bw-session action \"{other}\""))),
|
|
692
952
|
}
|
|
693
953
|
}
|
|
694
954
|
|
|
@@ -796,6 +1056,7 @@ fn get(
|
|
|
796
1056
|
name: &str,
|
|
797
1057
|
reason: Option<&str>,
|
|
798
1058
|
answer_stdin: bool,
|
|
1059
|
+
approval: Option<String>,
|
|
799
1060
|
) -> Outcome {
|
|
800
1061
|
let mut session = load_session(paths, token.as_deref())?;
|
|
801
1062
|
let store = open_store(paths)?;
|
|
@@ -814,14 +1075,32 @@ fn get(
|
|
|
814
1075
|
} else if session.grant(&item.name, now).is_some() {
|
|
815
1076
|
"existing-grant"
|
|
816
1077
|
} else {
|
|
1078
|
+
// The window is what the user approves: no caller-supplied text may
|
|
1079
|
+
// break out of its own line here.
|
|
817
1080
|
let message = format!(
|
|
818
1081
|
"条目: {}\n请求方: {}\n原因: {}\n\n允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
|
|
819
|
-
item.name,
|
|
820
|
-
session.requester,
|
|
821
|
-
reason.unwrap_or("(未说明)")
|
|
1082
|
+
dialog::for_dialog(&item.name, 80),
|
|
1083
|
+
dialog::for_dialog(&session.requester, 40),
|
|
1084
|
+
dialog::for_dialog(reason.unwrap_or("(未说明)"), 120)
|
|
822
1085
|
);
|
|
823
1086
|
let approved = if answer_stdin {
|
|
824
|
-
|
|
1087
|
+
// Relaying an answer is a host privilege: it must be signed with the
|
|
1088
|
+
// host secret, so the model's own bash cannot answer "y" for the user.
|
|
1089
|
+
let Some(secret) = host_secret().filter(|_| is_host()) else {
|
|
1090
|
+
audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), Some("unsigned-relay"));
|
|
1091
|
+
return Err(Fault::Usage(
|
|
1092
|
+
"--answer-stdin is only for a host that holds AI_VAULT_HOST_SECRET and signs the answer with --approval".into(),
|
|
1093
|
+
));
|
|
1094
|
+
};
|
|
1095
|
+
let answer = read_approval()?;
|
|
1096
|
+
let Some(approval) = approval else {
|
|
1097
|
+
return Err(Fault::Usage("--answer-stdin needs --approval <hmac of the answer>".into()));
|
|
1098
|
+
};
|
|
1099
|
+
if !approval_ok(&secret, &session.token, &item.name, answer, &approval) {
|
|
1100
|
+
audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), Some("bad-approval"));
|
|
1101
|
+
return Err(Fault::Denied(format!("approval signature mismatch for \"{}\"", item.name)));
|
|
1102
|
+
}
|
|
1103
|
+
answer
|
|
825
1104
|
} else {
|
|
826
1105
|
match dialog::confirm("ai-vault · 读取本地密码", &message) {
|
|
827
1106
|
Answer::Value(ok) => ok,
|
|
@@ -882,18 +1161,19 @@ fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outc
|
|
|
882
1161
|
if !req.yes {
|
|
883
1162
|
let mut meta = Vec::new();
|
|
884
1163
|
if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
885
|
-
meta.push(format!("用户名: {
|
|
1164
|
+
meta.push(format!("用户名: {}", dialog::for_dialog(user, 60)));
|
|
886
1165
|
}
|
|
887
1166
|
if let Some(uri) = req.uri.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
888
|
-
meta.push(format!("URI: {
|
|
1167
|
+
meta.push(format!("URI: {}", dialog::for_dialog(uri, 120)));
|
|
889
1168
|
}
|
|
890
1169
|
if let Some(notes) = req.notes.as_deref().map(str::trim).filter(|n| !n.is_empty()) {
|
|
891
|
-
meta.push(format!("备注: {
|
|
1170
|
+
meta.push(format!("备注: {}", dialog::for_dialog(notes, 120)));
|
|
892
1171
|
}
|
|
1172
|
+
let shown = dialog::for_dialog(&name, 80);
|
|
893
1173
|
let action = if existing.is_some() {
|
|
894
|
-
format!("更新已有条目「{
|
|
1174
|
+
format!("更新已有条目「{shown}」。")
|
|
895
1175
|
} else {
|
|
896
|
-
format!("新建条目「{
|
|
1176
|
+
format!("新建条目「{shown}」。")
|
|
897
1177
|
};
|
|
898
1178
|
let message = format!(
|
|
899
1179
|
"{action}{}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。",
|
|
@@ -991,7 +1271,7 @@ fn remove(paths: &Paths, out: &Out, token: Option<String>, name: &str, yes: bool
|
|
|
991
1271
|
return Err(Fault::Error(format!("no such entry: \"{name}\"")));
|
|
992
1272
|
}
|
|
993
1273
|
if !yes {
|
|
994
|
-
match dialog::confirm("ai-vault · 删除条目", &format!("删除「{
|
|
1274
|
+
match dialog::confirm("ai-vault · 删除条目", &format!("删除「{}」?删除后无法恢复。", dialog::for_dialog(name, 80))) {
|
|
995
1275
|
Answer::Value(true) => {}
|
|
996
1276
|
Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
|
|
997
1277
|
Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
|
|
@@ -1010,9 +1290,28 @@ fn remove(paths: &Paths, out: &Out, token: Option<String>, name: &str, yes: bool
|
|
|
1010
1290
|
Ok(())
|
|
1011
1291
|
}
|
|
1012
1292
|
|
|
1293
|
+
/// A grant is "no window for N minutes": it is a standing approval, so it
|
|
1294
|
+
/// costs the master password — the same as changing the unlock mode. The
|
|
1295
|
+
/// interactive `/vault grant` asks through the window; a non-host caller
|
|
1296
|
+
/// without the password cannot mint one.
|
|
1013
1297
|
fn grant(paths: &Paths, out: &Out, token: Option<String>, name: &str, minutes: Option<i64>) -> Outcome {
|
|
1014
1298
|
let mut session = load_session(paths, token.as_deref())?;
|
|
1015
1299
|
let store = open_store(paths)?;
|
|
1300
|
+
{
|
|
1301
|
+
// Only the host may use --password-stdin here (it just asked the user);
|
|
1302
|
+
// anyone else gets the window.
|
|
1303
|
+
let password = if is_host() {
|
|
1304
|
+
read_password()?
|
|
1305
|
+
} else {
|
|
1306
|
+
ask_password("ai-vault · 授权读取", "主密码(给一条条目免确认读取)")?
|
|
1307
|
+
};
|
|
1308
|
+
if let Err(e) = crypto::open_with_passphrase(&store, &password) {
|
|
1309
|
+
return Err(match e {
|
|
1310
|
+
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
1311
|
+
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1016
1315
|
let items = items_with(&session, &store)?;
|
|
1017
1316
|
let item = store::find(&items, name).ok_or_else(|| Fault::Error(format!("no such entry: \"{name}\"")))?;
|
|
1018
1317
|
let minutes = minutes.unwrap_or(GRANT_MS_DEFAULT / 60_000).clamp(1, GRANT_MS_MAX / 60_000);
|
|
@@ -1077,7 +1376,13 @@ fn import_file(paths: &Paths, out: &Out, token: Option<String>, file: &PathBuf,
|
|
|
1077
1376
|
let shown = drafts
|
|
1078
1377
|
.iter()
|
|
1079
1378
|
.take(15)
|
|
1080
|
-
.map(|d|
|
|
1379
|
+
.map(|d| {
|
|
1380
|
+
format!(
|
|
1381
|
+
"• {}{}",
|
|
1382
|
+
dialog::for_dialog(&d.name, 80),
|
|
1383
|
+
d.username.as_ref().map(|u| format!(" user:{}", dialog::for_dialog(u, 40))).unwrap_or_default()
|
|
1384
|
+
)
|
|
1385
|
+
})
|
|
1081
1386
|
.collect::<Vec<_>>()
|
|
1082
1387
|
.join("\n");
|
|
1083
1388
|
let more = if drafts.len() > 15 { format!("\n… 还有 {} 条", drafts.len() - 15) } else { String::new() };
|