@xiaolikt/ai-vault 0.11.0 → 0.12.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 CHANGED
@@ -14,7 +14,7 @@ dependencies = [
14
14
 
15
15
  [[package]]
16
16
  name = "ai-vault"
17
- version = "0.11.0"
17
+ version = "0.12.0"
18
18
  dependencies = [
19
19
  "base64",
20
20
  "chacha20poly1305",
package/README.md CHANGED
@@ -435,7 +435,7 @@ may *use* passwords but cannot *get around you* to take them.
435
435
  |---|---|---|
436
436
  | **You** (typing `ai-vault` in a terminal) | everything | — |
437
437
  | **The host** (the pi/omp extension process; `AI_VAULT_HOST=1` + a secret in memory) | relay your confirmations (signed), change settings | learn the master password unless you type it |
438
- | **The agent** (the model's `bash`, same user, can read `~/.ai-vault`) | read a token file (but a session the extension opened is useless without the secret — first use voids it) | **forge a read confirmation, mint a grant on a token, change the requester shown in a window, `list` an extension session, get the Bitwarden master password** |
438
+ | **The agent** (the model's `bash`, same user, can read `~/.ai-vault`) | read a token file (but a session the extension opened is useless without the secret — first use is refused) | **forge a read confirmation, mint a grant on a token, change the requester shown in a window, `list` an extension session, get the Bitwarden master password, change any setting by editing a file** |
439
439
  | **Another user / someone with the files offline** | read ciphertext | decrypt (scrypt + ChaCha20-Poly1305) |
440
440
 
441
441
  ### How
package/README.zh.md CHANGED
@@ -364,7 +364,7 @@ pi-ai-vault 只是这套 CLI 的客户端,本身不保存 Ente 的任何密钥
364
364
  |---|---|---|
365
365
  | **你**(终端里手敲 `ai-vault`) | 一切 | — |
366
366
  | **宿主**(pi/omp 扩展进程,持 `AI_VAULT_HOST=1` + 内存里的 host secret) | 替你转发确认(要签名)、改设置 | 不知道主密码(除非你输了) |
367
- | **agent**(模型的 `bash`,同一用户,能读 `~/.ai-vault`) | 读到会话令牌文件(但插件开的会话没有 secret 用不了,一用就作废) | **伪造一次读取确认、给令牌加授权、改确认窗里的请求方、`list` 插件会话、拿到 Bitwarden 主密码** |
367
+ | **agent**(模型的 `bash`,同一用户,能读 `~/.ai-vault`) | 读到会话令牌文件(但插件开的会话没有 secret,一用就被拒) | **伪造一次读取确认、给令牌加授权、改确认窗里的请求方、`list` 插件会话、拿到 Bitwarden 主密码、靠改文件改任何设置** |
368
368
  | **别的用户 / 离线拿到文件的人** | 读到密文 | 解密(scrypt + ChaCha20-Poly1305) |
369
369
 
370
370
  ### 怎么做到的
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ai-vault"
3
- version = "0.11.0"
3
+ version = "0.12.0"
4
4
  edition = "2021"
5
5
  description = "Machine-wide encrypted secret store shared by AI coding agents"
6
6
  license = "MIT"
@@ -70,24 +70,32 @@ enum Cmd {
70
70
  },
71
71
  /// Show or change machine-wide settings
72
72
  Settings {
73
- /// Dotted key (vault.unlock, vault.hours, bitwarden.unlock,
74
- /// bitwarden.hours, bitwarden.import); omit to print everything
73
+ /// Dotted key (vault.unlock, vault.hours, vault.confirm,
74
+ /// bitwarden.unlock, bitwarden.hours, bitwarden.import, ente.*); omit
75
+ /// to print everything
75
76
  key: Option<String>,
76
77
  /// New value; omit to print the current one
77
78
  value: Option<String>,
78
- /// Read the vault master password from stdin (changing vault.unlock)
79
+ /// Read the vault master password from stdin (for the changes that need it)
79
80
  #[arg(long)]
80
81
  password_stdin: bool,
82
+ #[arg(long, env = "AI_VAULT_TOKEN")]
83
+ token: Option<String>,
81
84
  },
82
85
  /// The persisted `bw` session key (bitwarden.unlock = never | time)
83
86
  BwSession {
84
87
  /// get | put | clear
85
88
  action: String,
89
+ /// `put` reads the policy from the store, so it needs an unlocked session
90
+ #[arg(long, env = "AI_VAULT_TOKEN")]
91
+ token: Option<String>,
86
92
  },
87
93
  /// Ente's `ENTE_CLI_VAULT_KEY` (ente.unlock = never | time)
88
94
  EnteSession {
89
95
  /// get | put | clear
90
96
  action: String,
97
+ #[arg(long, env = "AI_VAULT_TOKEN")]
98
+ token: Option<String>,
91
99
  },
92
100
  /// Show or change how often the master password is asked for
93
101
  Mode {
@@ -102,6 +110,8 @@ enum Cmd {
102
110
  /// Read the master password from stdin (changing the mode needs it)
103
111
  #[arg(long)]
104
112
  password_stdin: bool,
113
+ #[arg(long, env = "AI_VAULT_TOKEN")]
114
+ token: Option<String>,
105
115
  },
106
116
  /// Session state, item count, and remaining read grants
107
117
  Status {
@@ -342,13 +352,13 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
342
352
  Cmd::Unlock { password_stdin, requester, idle_min } => {
343
353
  unlock(paths, &out, password_stdin, &requester, idle_min)
344
354
  }
345
- Cmd::Settings { key, value, password_stdin } => {
346
- settings(paths, &out, key.as_deref(), value.as_deref(), None, password_stdin)
355
+ Cmd::Settings { key, value, password_stdin, token } => {
356
+ settings(paths, &out, token.as_deref(), key.as_deref(), value.as_deref(), None, password_stdin)
347
357
  }
348
- Cmd::BwSession { action } => sealed_session(paths, &out, Kind::Bitwarden, &action),
349
- Cmd::EnteSession { action } => sealed_session(paths, &out, Kind::Ente, &action),
350
- Cmd::Mode { action, value, hours, password_stdin } => {
351
- mode(paths, &out, &action, value.as_deref(), hours, password_stdin)
358
+ Cmd::BwSession { action, token } => sealed_session(paths, &out, Kind::Bitwarden, &action, token.as_deref()),
359
+ Cmd::EnteSession { action, token } => sealed_session(paths, &out, Kind::Ente, &action, token.as_deref()),
360
+ Cmd::Mode { action, value, hours, password_stdin, token } => {
361
+ mode(paths, &out, token.as_deref(), &action, value.as_deref(), hours, password_stdin)
352
362
  }
353
363
  Cmd::Status { token } => status(paths, &out, token),
354
364
  Cmd::Lock { token, all } => lock(paths, &out, token, all),
@@ -404,8 +414,8 @@ fn idle_ms(minutes: Option<i64>) -> i64 {
404
414
  /// time -> absolute deadline, `hours` from now
405
415
  /// session -> no deadline, with a 7-day ceiling in case an agent dies
406
416
  /// without locking
407
- fn policy(paths: &Paths, idle_min: Option<i64>) -> (i64, Option<i64>, UnlockPolicy) {
408
- let policy = config::load(paths).unlock;
417
+ fn policy(idle_min: Option<i64>, config: &config::Config) -> (i64, Option<i64>, UnlockPolicy) {
418
+ let policy = config.unlock;
409
419
  if let Some(minutes) = idle_min {
410
420
  return (idle_ms(Some(minutes)), None, policy);
411
421
  }
@@ -497,6 +507,10 @@ fn open_store(paths: &Paths) -> Result<crypto::StoreFile, Fault> {
497
507
  }
498
508
 
499
509
  fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>, Fault> {
510
+ Ok(payload_with(session, store)?.items)
511
+ }
512
+
513
+ fn payload_with(session: &Session, store: &crypto::StoreFile) -> Result<crypto::Payload, Fault> {
500
514
  let key = session
501
515
  .key()
502
516
  .ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
@@ -506,6 +520,19 @@ fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>,
506
520
  })
507
521
  }
508
522
 
523
+ /// Write the settings back into the store under this session's key.
524
+ fn config_write(paths: &Paths, session: &Session, config: &config::Config) -> Result<(), Fault> {
525
+ let _guard = StoreLock::acquire(paths)?;
526
+ let store = open_store(paths)?;
527
+ let key = session
528
+ .key()
529
+ .ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
530
+ let sealed = config::write_with(&store, &key, config)?;
531
+ let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
532
+ crypto::write_atomic(&paths.store(), &bytes)?;
533
+ Ok(())
534
+ }
535
+
509
536
  /// The secret the host process (pi/omp extension) holds and passes to each
510
537
  /// CLI call through the environment. A bare `ai-vault` typed by a human has
511
538
  /// none, which is fine: that caller never needs to relay an approval.
@@ -513,13 +540,18 @@ fn host_secret() -> Option<String> {
513
540
  std::env::var("AI_VAULT_HOST_SECRET").ok().filter(|s| !s.is_empty())
514
541
  }
515
542
 
516
- /// What session files are signed with: the host's memory-only secret when
517
- /// there is one, else the store's wrap key (a human at a terminal).
518
- fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
519
- if let Some(secret) = host_secret() {
520
- return Ok(Some(secret));
543
+ /// What a session file is signed with: the host's memory-only secret when
544
+ /// the caller presented one, else the store's wrap key (a human at a terminal).
545
+ fn signer(paths: &Paths) -> Result<session::Signer, String> {
546
+ match host_secret() {
547
+ Some(secret) => Ok(session::Signer::Host(secret)),
548
+ None => sealed::wrap_key_hex(paths).map(session::Signer::Wrap),
521
549
  }
522
- sealed::wrap_key_hex(paths).map(Some)
550
+ }
551
+
552
+ /// Both keys, for checking a file against whichever one signed it.
553
+ fn signing_keys(paths: &Paths) -> Result<(Option<String>, Option<String>), String> {
554
+ Ok((host_secret(), Some(sealed::wrap_key_hex(paths)?)))
523
555
  }
524
556
 
525
557
  /// The host integration (the extension) is recognised by the secret it
@@ -553,7 +585,8 @@ fn auto_session(paths: &Paths) -> Option<Session> {
553
585
  /// An explicit token, else the machine-wide auto session.
554
586
  fn load_session(paths: &Paths, token: Option<&str>) -> Result<Session, Fault> {
555
587
  if let Some(token) = token.filter(|t| !t.is_empty()) {
556
- return session::load(paths, token, signing_key(paths)?.as_deref()).map_err(Fault::Auth);
588
+ let (host, wrap) = signing_keys(paths)?;
589
+ return session::load(paths, token, host.as_deref(), wrap.as_deref()).map_err(Fault::Auth);
557
590
  }
558
591
  auto_session(paths).ok_or_else(|| {
559
592
  Fault::Auth("vault is locked (no session token) — unlock first".into())
@@ -572,8 +605,8 @@ fn persist(paths: &Paths, session: &Session) {
572
605
  } else {
573
606
  // Best-effort like the rest of this helper; a failed sign means the
574
607
  // next call simply asks to unlock again.
575
- match signing_key(paths) {
576
- Ok(key) => session.save(paths, key.as_deref()),
608
+ match signer(paths) {
609
+ Ok(signer) => session.save(paths, &signer),
577
610
  Err(e) => Err(e),
578
611
  }
579
612
  };
@@ -593,14 +626,14 @@ where
593
626
  {
594
627
  let _guard = StoreLock::acquire(paths)?;
595
628
  let store = open_store(paths)?;
596
- let mut items = items_with(session, &store)?;
629
+ let mut payload = payload_with(session, &store)?;
597
630
  let now = store::now_iso();
598
- f(&mut items, &now)?;
631
+ f(&mut payload.items, &now)?;
599
632
  let key = session
600
633
  .key()
601
634
  .ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
602
635
  let salt = crypto::hex_to_bytes(&session.salt).ok_or_else(|| Fault::Error("session salt is corrupt".into()))?;
603
- let sealed = crypto::seal(&salt, session.kdf.unwrap_or_default(), &key, &items)?;
636
+ let sealed = crypto::seal(&salt, session.kdf.unwrap_or_default(), &key, &payload.items, &payload.config)?;
604
637
  let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
605
638
  crypto::write_atomic(&paths.store(), &bytes)?;
606
639
  Ok(())
@@ -618,14 +651,14 @@ fn rekey(paths: &Paths, out: &Out, password_stdin: bool) -> Outcome {
618
651
  } else {
619
652
  ask_password(tr("ai-vault · upgrade key parameters", "ai-vault · 升级密钥参数"), tr("master password", "主密码"))?
620
653
  };
621
- let (items, _old_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
654
+ let (payload, _old_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
622
655
  crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
623
656
  crypto::OpenError::Broken(message) => Fault::Error(message),
624
657
  })?;
625
658
  let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| Fault::Error("vault salt is corrupt".into()))?;
626
659
  let kdf = Kdf::default();
627
660
  let new_key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
628
- let sealed = crypto::seal(&salt, kdf, &new_key, &items)?;
661
+ let sealed = crypto::seal(&salt, kdf, &new_key, &payload.items, &payload.config)?;
629
662
  {
630
663
  let _guard = StoreLock::acquire(paths)?;
631
664
  let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
@@ -634,7 +667,7 @@ fn rekey(paths: &Paths, out: &Out, password_stdin: bool) -> Outcome {
634
667
  // Other live sessions hold the old key; they cannot open the new file and
635
668
  // will be told to unlock again. The machine session is simply re-minted.
636
669
  let _ = session::delete_auto(paths);
637
- if config::load(paths).unlock.mode == UnlockMode::Never {
670
+ if payload.config.unlock.mode == UnlockMode::Never {
638
671
  let auto = Session::new("rekey", 0, None, &sealed, &new_key);
639
672
  session::save_auto(paths, &auto)?;
640
673
  }
@@ -655,7 +688,6 @@ fn doctor(paths: &Paths, out: &Out) -> Outcome {
655
688
  "audit": paths.audit(),
656
689
  "display": dialog::has_display(),
657
690
  "zenity": which("zenity"),
658
- "mode": config::load(paths).unlock.mode.as_str(),
659
691
  "auto": paths.auto_session().exists(),
660
692
  "kdf": crypto::read_store(&paths.store()).ok().flatten().map(|s| s.kdf().n),
661
693
  });
@@ -702,7 +734,11 @@ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_mi
702
734
  let salt = crypto::random_bytes::<16>();
703
735
  let kdf = Kdf::default();
704
736
  let key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
705
- let sealed = crypto::seal(&salt, kdf, &key, &[])?;
737
+ let mut config = config::Config::default();
738
+ if let Some(legacy) = config::take_legacy(paths) {
739
+ config = legacy;
740
+ }
741
+ let sealed = crypto::seal(&salt, kdf, &key, &[], &config)?;
706
742
  {
707
743
  let _guard = StoreLock::acquire(paths)?;
708
744
  if paths.store().exists() {
@@ -712,13 +748,13 @@ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_mi
712
748
  crypto::write_atomic(&paths.store(), &bytes)?;
713
749
  }
714
750
  session::ensure_session_dir(paths)?;
715
- let (idle, deadline, policy) = policy(paths, idle_min);
716
- let secret = signing_key(paths)?;
751
+ let (idle, deadline, policy) = policy(idle_min, &config);
717
752
  let session = Session::new(requester, idle, deadline, &sealed, &key);
718
753
  if policy.mode == UnlockMode::Never {
719
754
  session::save_auto(paths, &session)?;
720
755
  } else {
721
- session.save(paths, secret.as_deref())?;
756
+ let signer = signer(paths)?;
757
+ session.save(paths, &signer)?;
722
758
  }
723
759
  audit::append(&paths.audit(), requester, "init", None, None);
724
760
  let value = json!({
@@ -742,26 +778,38 @@ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_
742
778
  } else {
743
779
  ask_password(tr("ai-vault · unlock", "ai-vault · 解锁"), tr("local store master password", "本地库主密码"))?
744
780
  };
745
- let (items, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
781
+ let (mut payload, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
746
782
  crypto::OpenError::WrongPassword => {
747
783
  audit::append(&paths.audit(), requester, "unlock_failed", None, Some("bad-password"));
748
784
  Fault::Auth("wrong master password".into())
749
785
  }
750
786
  crypto::OpenError::Broken(message) => Fault::Error(message),
751
787
  })?;
788
+ let items = payload.items;
789
+ // A plaintext config.json from an older version is brought inside the
790
+ // store now that the password has been verified — minus anything that
791
+ // lowers protection, which a file edit must never grant.
792
+ let migrated = config::take_legacy(paths).map(|legacy| {
793
+ payload.config = legacy;
794
+ true
795
+ });
796
+ if migrated == Some(true) {
797
+ let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| Fault::Error("vault salt is corrupt".into()))?;
798
+ let sealed = crypto::seal(&salt, store.kdf(), &key, &items, &payload.config)?;
799
+ let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
800
+ crypto::write_atomic(&paths.store(), &bytes)?;
801
+ }
752
802
  session::ensure_session_dir(paths)?;
753
803
  session::sweep(paths);
754
- let (idle, deadline, policy) = policy(paths, idle_min);
755
- // A host that did not pass a secret gets a fresh one to keep for this
756
- // session: it is the only thing that can sign later edits to the file.
804
+ let (idle, deadline, policy) = policy(idle_min, &payload.config);
757
805
  // The host brings its own secret (so the same process can sign later
758
806
  // calls); everyone else is signed with the wrap key.
759
- let secret = signing_key(paths)?;
760
807
  let session = Session::new(requester, idle, deadline, &store, &key);
761
808
  if policy.mode == UnlockMode::Never {
762
809
  session::save_auto(paths, &session)?;
763
810
  } else {
764
- session.save(paths, secret.as_deref())?;
811
+ let signer = signer(paths)?;
812
+ session.save(paths, &signer)?;
765
813
  }
766
814
  audit::append(&paths.audit(), requester, "unlock", None, Some(policy.mode.as_str()));
767
815
  let value = json!({
@@ -784,6 +832,7 @@ fn setting_key(raw: &str) -> Option<&'static str> {
784
832
  match raw.trim().to_lowercase().as_str() {
785
833
  "vault.unlock" | "vault.mode" | "unlock" | "mode" => Some("vault.unlock"),
786
834
  "vault.hours" | "hours" => Some("vault.hours"),
835
+ "vault.confirm" | "confirm" => Some("vault.confirm"),
787
836
  "bitwarden.unlock" | "bitwarden.mode" | "bw.unlock" | "bw.mode" => Some("bitwarden.unlock"),
788
837
  "bitwarden.hours" | "bw.hours" => Some("bitwarden.hours"),
789
838
  "bitwarden.import" | "bw.import" | "import" => Some("bitwarden.import"),
@@ -801,6 +850,7 @@ fn settings_value(config: &config::Config, paths: &Paths) -> serde_json::Value {
801
850
  "vault": {
802
851
  "unlock": config.unlock.mode.as_str(),
803
852
  "hours": config.unlock.hours,
853
+ "confirm": config.unlock.confirm,
804
854
  "auto": paths.auto_session().exists(),
805
855
  },
806
856
  "bitwarden": {
@@ -824,6 +874,11 @@ fn settings_human(config: &config::Config, paths: &Paths) -> String {
824
874
  [
825
875
  format!("vault.unlock: {} (never | time | session)", config.unlock.mode.as_str()),
826
876
  format!("vault.hours: {}{}", config.unlock.hours, tr(" (time mode)", " (time 模式)")),
877
+ format!(
878
+ "vault.confirm: {}{}",
879
+ config.unlock.confirm,
880
+ tr(" (a window per read while unlocked)", " (解锁后每次读取弹确认窗)")
881
+ ),
827
882
  format!("{} {}", tr("vault machine-wide session:", "vault 机器级会话:"), if paths.auto_session().exists() { tr("yes (no password)", "有(免密)") } else { tr("no", "无") }),
828
883
  format!("bitwarden.unlock: {} (never | time | session)", config.bitwarden.store.unlock.as_str()),
829
884
  format!("bitwarden.hours: {}", config.bitwarden.store.hours),
@@ -851,12 +906,18 @@ fn settings_human(config: &config::Config, paths: &Paths) -> String {
851
906
  fn settings(
852
907
  paths: &Paths,
853
908
  out: &Out,
909
+ token: Option<&str>,
854
910
  key: Option<&str>,
855
911
  value: Option<&str>,
856
912
  hours: Option<i64>,
857
913
  password_stdin: bool,
858
914
  ) -> Outcome {
859
- let mut config = config::load(paths);
915
+ // The settings live inside the store's ciphertext: reading them needs the
916
+ // store's key, i.e. an unlocked session. That is the whole point — there
917
+ // is no file an agent could edit.
918
+ let session = load_session(paths, token)?;
919
+ let store = open_store(paths)?;
920
+ let mut config = payload_with(&session, &store)?.config;
860
921
 
861
922
  let Some(raw_key) = key.filter(|k| !k.trim().is_empty()) else {
862
923
  let value = settings_value(&config, paths);
@@ -873,6 +934,7 @@ fn settings(
873
934
  let shown = match key {
874
935
  "vault.unlock" => config.unlock.mode.as_str().to_string(),
875
936
  "vault.hours" => config.unlock.hours.to_string(),
937
+ "vault.confirm" => config.unlock.confirm.to_string(),
876
938
  "bitwarden.unlock" => config.bitwarden.store.unlock.as_str().to_string(),
877
939
  "bitwarden.hours" => config.bitwarden.store.hours.to_string(),
878
940
  "ente.unlock" => config.ente.unlock.as_str().to_string(),
@@ -887,19 +949,13 @@ fn settings(
887
949
  "vault.unlock" => {
888
950
  let mode = UnlockMode::parse(raw_value)
889
951
  .ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
890
- let store = open_store(paths)?;
891
952
  // Changing when the vault opens is a security decision: always verify.
892
- let password = if password_stdin {
893
- read_password()?
894
- } else {
895
- ask_password(tr("ai-vault · master password", "ai-vault · 主密码"), tr("switching the unlock policy", "切换解锁模式"))?
896
- };
897
- let (_, vault_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
898
- crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
899
- crypto::OpenError::Broken(message) => Fault::Error(message),
900
- })?;
901
- config.unlock = UnlockPolicy { mode, hours: hours.unwrap_or(config.unlock.hours).clamp(1, 24 * 90) };
902
- config::save(paths, &config)?;
953
+ let (payload, vault_key) = verify_master(paths, &store, password_stdin, tr("switching the unlock policy", "切换解锁模式"))?;
954
+ config.unlock.mode = mode;
955
+ if let Some(hours) = hours {
956
+ config.unlock.hours = hours.clamp(1, 24 * 90);
957
+ }
958
+ config_write(paths, &session, &config)?;
903
959
  session::ensure_session_dir(paths)?;
904
960
  if mode == UnlockMode::Never {
905
961
  let auto = Session::new("mode", 0, None, &store, &vault_key);
@@ -907,6 +963,7 @@ fn settings(
907
963
  } else {
908
964
  session::delete_auto(paths);
909
965
  }
966
+ let _ = payload;
910
967
  audit::append(&paths.audit(), "cli", "mode", None, Some(mode.as_str()));
911
968
  }
912
969
  "vault.hours" => {
@@ -914,16 +971,36 @@ fn settings(
914
971
  .parse()
915
972
  .map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
916
973
  config.unlock.hours = hours.clamp(1, 24 * 90);
917
- config::save(paths, &config)?;
974
+ config_write(paths, &session, &config)?;
975
+ }
976
+ "vault.confirm" => {
977
+ // Turning the per-read window off is a security decision, priced
978
+ // like the unlock policy: the master password.
979
+ let on = matches!(raw_value, "true" | "1" | "yes" | "on" | "ask")
980
+ || if matches!(raw_value, "false" | "0" | "no" | "off") {
981
+ false
982
+ } else {
983
+ return Err(Fault::Usage(format!("\"{raw_value}\" is not true or false")));
984
+ };
985
+ if !on {
986
+ verify_master(paths, &store, password_stdin, tr("turn off the per-read confirmation", "关闭每次读取的确认窗"))?;
987
+ }
988
+ config.unlock.confirm = on;
989
+ config_write(paths, &session, &config)?;
990
+ audit::append(&paths.audit(), "cli", "settings", None, Some(if on { "confirm=on" } else { "confirm=off" }));
918
991
  }
919
992
  "bitwarden.unlock" => {
920
993
  let mode = UnlockMode::parse(raw_value)
921
994
  .ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
995
+ // Keeping the bw session key on disk is a downgrade of its own.
996
+ if mode != UnlockMode::Session {
997
+ verify_master(paths, &store, password_stdin, tr("keeping the Bitwarden session on disk", "把 Bitwarden 会话落盘"))?;
998
+ }
922
999
  config.bitwarden.store.unlock = mode;
923
1000
  if let Some(hours) = hours {
924
1001
  config.bitwarden.store.hours = hours.clamp(1, 24 * 90);
925
1002
  }
926
- config::save(paths, &config)?;
1003
+ config_write(paths, &session, &config)?;
927
1004
  // Going back to per-session must not leave a key on disk.
928
1005
  if mode == UnlockMode::Session {
929
1006
  sealed::clear(paths, Kind::Bitwarden);
@@ -934,16 +1011,19 @@ fn settings(
934
1011
  .parse()
935
1012
  .map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
936
1013
  config.bitwarden.store.hours = hours.clamp(1, 24 * 90);
937
- config::save(paths, &config)?;
1014
+ config_write(paths, &session, &config)?;
938
1015
  }
939
1016
  "ente.unlock" => {
940
1017
  let mode = UnlockMode::parse(raw_value)
941
1018
  .ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
1019
+ if mode != UnlockMode::Session {
1020
+ verify_master(paths, &store, password_stdin, tr("keeping the Ente key on disk", "把 Ente 密钥落盘"))?;
1021
+ }
942
1022
  config.ente.unlock = mode;
943
1023
  if let Some(hours) = hours {
944
1024
  config.ente.hours = hours.clamp(1, 24 * 90);
945
1025
  }
946
- config::save(paths, &config)?;
1026
+ config_write(paths, &session, &config)?;
947
1027
  if mode == UnlockMode::Session {
948
1028
  sealed::clear(paths, Kind::Ente);
949
1029
  }
@@ -953,14 +1033,18 @@ fn settings(
953
1033
  .parse()
954
1034
  .map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
955
1035
  config.ente.hours = hours.clamp(1, 24 * 90);
956
- config::save(paths, &config)?;
1036
+ config_write(paths, &session, &config)?;
957
1037
  }
958
1038
  _ => {
959
1039
  let import = ImportPolicy::parse(raw_value).ok_or_else(|| {
960
1040
  Fault::Usage(format!("unknown import policy \"{raw_value}\" — ask, always or never"))
961
1041
  })?;
1042
+ // "always" imports a Bitwarden hit with no window: a downgrade.
1043
+ if import == ImportPolicy::Always {
1044
+ verify_master(paths, &store, password_stdin, tr("importing Bitwarden hits without asking", "不询问就导入 Bitwarden 条目"))?;
1045
+ }
962
1046
  config.bitwarden.import = import;
963
- config::save(paths, &config)?;
1047
+ config_write(paths, &session, &config)?;
964
1048
  }
965
1049
  }
966
1050
 
@@ -969,23 +1053,47 @@ fn settings(
969
1053
  Ok(())
970
1054
  }
971
1055
 
1056
+ /// Ask for the master password and prove it against the store. Used for
1057
+ /// every change that lowers protection. Returns the opened payload and the
1058
+ /// key, for the one caller that mints the machine-wide session.
1059
+ fn verify_master(
1060
+ paths: &Paths,
1061
+ store: &crypto::StoreFile,
1062
+ password_stdin: bool,
1063
+ why: &str,
1064
+ ) -> Result<(crypto::Payload, crypto::Key), Fault> {
1065
+ let password = if password_stdin {
1066
+ read_password()?
1067
+ } else {
1068
+ ask_password(tr("ai-vault · master password", "ai-vault · 主密码"), why)?
1069
+ };
1070
+ crypto::open_with_passphrase(store, &password).map_err(|e| match e {
1071
+ crypto::OpenError::WrongPassword => {
1072
+ audit::append(&paths.audit(), "cli", "settings", None, Some("denied=bad-password"));
1073
+ Fault::Auth("wrong master password".into())
1074
+ }
1075
+ crypto::OpenError::Broken(message) => Fault::Error(message),
1076
+ })
1077
+ }
1078
+
972
1079
  /// `/vault mode` is a shortcut for the `vault.unlock` setting.
973
1080
  fn mode(
974
1081
  paths: &Paths,
975
1082
  out: &Out,
1083
+ token: Option<&str>,
976
1084
  action: &str,
977
1085
  value: Option<&str>,
978
1086
  hours: Option<i64>,
979
1087
  password_stdin: bool,
980
1088
  ) -> Outcome {
981
1089
  match action.trim() {
982
- "" | "get" | "status" => settings(paths, out, Some("vault.unlock"), None, None, password_stdin),
983
- "set" => settings(paths, out, Some("vault.unlock"), value, hours, password_stdin),
1090
+ "" | "get" | "status" => settings(paths, out, token, Some("vault.unlock"), None, None, password_stdin),
1091
+ "set" => settings(paths, out, token, Some("vault.unlock"), value, hours, password_stdin),
984
1092
  other => Err(Fault::Usage(format!("unknown mode action \"{other}\""))),
985
1093
  }
986
1094
  }
987
1095
 
988
- fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome {
1096
+ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str, token: Option<&str>) -> Outcome {
989
1097
  match action.trim() {
990
1098
  "" | "get" => {
991
1099
  let stored = sealed::load(paths, kind)?
@@ -1003,7 +1111,14 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
1003
1111
  if key.is_empty() {
1004
1112
  return Err(Fault::Usage("bw-session put expects the session key on stdin".into()));
1005
1113
  }
1006
- let expires_at = sealed::save(paths, kind, &key)?;
1114
+ let session = load_session(paths, token)?;
1115
+ let store = open_store(paths)?;
1116
+ let payload = payload_with(&session, &store)?;
1117
+ let policy = match kind {
1118
+ Kind::Bitwarden => payload.config.bitwarden.store,
1119
+ Kind::Ente => payload.config.ente,
1120
+ };
1121
+ let expires_at = sealed::save(paths, kind, &key, policy)?;
1007
1122
  audit::append(&paths.audit(), "cli", "sealed", None, Some(secret_kind_label(kind)));
1008
1123
  out.value(json!({ "ok": true, "expiresAt": expires_at }), || {
1009
1124
  match expires_at {
@@ -1038,7 +1153,7 @@ fn status(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
1038
1153
  .iter()
1039
1154
  .map(|(name, until)| (name.clone(), json!({ "expiresAt": until, "leftMs": until - now })))
1040
1155
  .collect();
1041
- let policy = config::load(paths).unlock;
1156
+ let policy = payload_with(&session, &store)?.config.unlock;
1042
1157
  let auto = session::load_auto(paths)
1043
1158
  .ok()
1044
1159
  .flatten()
@@ -1052,6 +1167,7 @@ fn status(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
1052
1167
  "expiresAt": session.expiry(),
1053
1168
  "mode": policy.mode.as_str(),
1054
1169
  "hours": policy.hours,
1170
+ "confirm": policy.confirm,
1055
1171
  "auto": auto,
1056
1172
  "store": paths.store(),
1057
1173
  "grants": grants,
@@ -1141,7 +1257,8 @@ fn get(
1141
1257
  ) -> Outcome {
1142
1258
  let mut session = load_session(paths, token.as_deref())?;
1143
1259
  let store = open_store(paths)?;
1144
- let items = items_with(&session, &store)?;
1260
+ let payload = payload_with(&session, &store)?;
1261
+ let items = payload.items;
1145
1262
  let item = store::find(&items, name).cloned().ok_or_else(|| {
1146
1263
  let names = items.iter().map(|i| i.name.clone()).collect::<Vec<_>>().join(", ");
1147
1264
  Fault::Error(format!("no such entry: \"{name}\". available: {}", if names.is_empty() { "(empty)" } else { &names }))
@@ -1151,8 +1268,17 @@ fn get(
1151
1268
  // `never` mode is the "the agent may use these freely" mode: the machine-wide
1152
1269
  // session is the authorization, so no window opens on each read.
1153
1270
  let auto = token.as_deref().map_or(true, |t| t.trim().is_empty());
1271
+ // `vault.confirm = false`: the master password that opened this session is
1272
+ // the approval. Safe for exactly that reason — a session the extension
1273
+ // opened can only exist because the user typed the password (a token the
1274
+ // model finds on disk is useless without the host secret). Every read is
1275
+ // still written to the audit log, entry by entry.
1276
+ let no_confirm = payload.config.unlock.confirm == false;
1154
1277
  let via = if auto {
1155
1278
  "no-password"
1279
+ } else if no_confirm {
1280
+ audit::append(&paths.audit(), &session.requester, "read_allow", Some(&item.name), Some("confirm-off"));
1281
+ "unlocked-no-confirm"
1156
1282
  } else if session.grant(&item.name, now).is_some() {
1157
1283
  "existing-grant"
1158
1284
  } else {