@xiaolikt/ai-vault 0.5.0 → 0.6.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.5.0"
17
+ version = "0.6.0"
18
18
  dependencies = [
19
19
  "base64",
20
20
  "chacha20poly1305",
package/README.md CHANGED
@@ -93,6 +93,8 @@ ai-vault [--dir DIR] [--json] <命令>
93
93
  | `init [--password-stdin]` | 建库(弹窗两次设密码),成功后直接给一个令牌 |
94
94
  | `unlock [--password-stdin] [--requester ID]` | 按当前模式解锁,stdout 一个令牌 |
95
95
  | `mode [get]` / `mode set never\|time\|session [--hours N]` | 查看/切换解锁模式(切换要主密码) |
96
+ | `settings [键] [值]` | 全部设置:`vault.unlock` `vault.hours` `bitwarden.unlock` `bitwarden.hours` `bitwarden.import` |
97
+ | `bw-session get\|put\|clear` | Bitwarden 会话密钥的落盘副本(`bitwarden.unlock != session` 时用) |
96
98
  | `status --token T` | 条目数、过期时间、还活着的读授权 |
97
99
  | `lock --token T \| --all` | 丢掉令牌(`--all` 清空本机所有会话) |
98
100
  | `list --token T` | 条目元数据(名称/用户名/URI),没有密码 |
@@ -124,7 +126,7 @@ ai-vault [--dir DIR] [--json] <命令>
124
126
  | 工具 | 作用 | 等级 | 模型看到密码? |
125
127
  |---|---|---|---|
126
128
  | `vault_list` | 本地库元数据 | read | 否 |
127
- | `vault_get` | 读一条:**先本地库,再 Bitwarden**;Bitwarden 命中会问「读一次 / 导入」 | exec | 是,用户当场允许 |
129
+ | `vault_get` | 读一条:**先本地库,再 Bitwarden**;命中后按 `bitwarden.import` 处理(问 / 直接导入 / 只读一次) | exec | 是,用户当场允许 |
128
130
  | `vault_add` | 存一条;密码在弹窗里输入 | write | 否 |
129
131
  | `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | write | 否 |
130
132
  | `bw_list` | 查在线 Bitwarden 元数据 | read | 否 |
@@ -170,12 +172,36 @@ ai-vault mode set session
170
172
 
171
173
  `never` 不是「安全一点」而是「明确放弃这层保护」:任何能读你 home 目录的进程都能读出库里的全部密码。它存在的意义是把「可以让 AI 随便用」的密码和 Bitwarden 里那些「每次都要问」的分开。
172
174
 
175
+ ### Bitwarden 也是同样三种模式(独立设置)
176
+
177
+ | 设置 | 值 | 行为 |
178
+ |---|---|---|
179
+ | `bitwarden.unlock` | `never` | `bw` 会话密钥落盘(`~/.ai-vault/bitwarden.session.json`,0600),**不再问 Bitwarden 主密码** |
180
+ | | `time` | 同上,但 `bitwarden.hours` 小时后失效,重新要密码 |
181
+ | | `session` | 密钥只在 agent 进程内存里,每个会话问一次(默认) |
182
+ | `bitwarden.import` | `ask` | `vault_get` 本地没命中 → 显示 Bitwarden 命中项 → 读一次 → 问是否导入(默认) |
183
+ | | `always` | 命中就直接导入并返回,**一个窗口都不开**(完全自动,慎用) |
184
+ | | `never` | 只读一次,问一次,永不写入本地库 |
185
+
186
+ ```bash
187
+ ai-vault settings # 全部设置
188
+ ai-vault settings bitwarden.unlock never
189
+ ai-vault settings bitwarden.import always
190
+ ai-vault settings bitwarden.hours 24
191
+ ```
192
+ 插件里:`/vault settings`、`/vault settings bitwarden.import always`。
193
+
194
+ > `bitwarden.import = always` 配合 `bitwarden.unlock = never`,等于「Bitwarden 里任何一条被问到就自动进库、以后免密随便读」。这是最快也是最不设防的组合,只在完全信任 agent 时用。
195
+
196
+ `bw-session put/get/clear` 就是那个落盘密钥的读写口:插件在主密码解锁成功后写入,切回 `session` 模式时自动清掉,`/bw lock` 也会清掉。
197
+
173
198
  ## 插件里的命令
174
199
 
175
200
  ```
176
201
  /vault init 创建本地库(弹窗设主密码)
177
202
  /vault unlock | lock 解锁 / 锁定本会话
178
203
  /vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)
204
+ /vault settings [键 值] 查看/修改设置(bitwarden.* 也在这里)
179
205
  /vault status 状态、过期时间、授权剩余
180
206
  /vault list 条目元数据
181
207
  /vault add [名称] 新增(用户名、密码在弹窗里输入)
@@ -208,7 +234,7 @@ ai-vault mode set session
208
234
 
209
235
  ## 安全
210
236
 
211
- - 主密码只经过弹窗或宿主输入框;`unlock` 派生出的 key 只写进令牌文件(0600,优先 tmpfs,登出即消失)。`never` 模式例外:key 写在 `~/.ai-vault/agent.session.json`,跨重启存在——这是那个模式的定义,不是疏漏。它和「agent 进程内存里有 key」是同一级别的暴露面,好处是换会话、reload、崩溃都会自然清掉。
237
+ - 主密码只经过弹窗或宿主输入框;`unlock` 派生出的 key 只写进令牌文件(0600,优先 tmpfs,登出即消失)。`never` 模式例外:key 写在 `~/.ai-vault/agent.session.json`,跨重启存在——这是那个模式的定义,不是疏漏。Bitwarden 侧同理:`bitwarden.unlock = never|time` 会把 `bw` 会话密钥写到 `~/.ai-vault/bitwarden.session.json`(0600),它是 bearer token,丢了等于丢了那次登录。它和「agent 进程内存里有 key」是同一级别的暴露面,好处是换会话、reload、崩溃都会自然清掉。
212
238
  - 会话令牌只是 id,不是 key:泄露令牌不等于泄露密码,但仍能读库,所以 `lock` 要真删文件。
213
239
  - 插件启动的子进程(`bw`、`bw_run` 的 bash、剪贴板工具)都会剔除宿主环境里的 `BW_*`,避免用户 shell 里导出的会话密钥漏进命令环境。
214
240
  - 审计:`~/.ai-vault/audit.log` 记录会话/子代理标签、条目名、允许/拒绝,从不记录值;写失败不影响主操作;1 MiB 轮转成 `.1`。
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ai-vault"
3
- version = "0.5.0"
3
+ version = "0.6.0"
4
4
  edition = "2021"
5
5
  description = "Machine-wide encrypted secret store shared by AI coding agents"
6
6
  license = "MIT"
@@ -0,0 +1,82 @@
1
+ //! The `bw` session key, persisted for `bitwarden.unlock = never | time`.
2
+ //!
3
+ //! `bw unlock` hands back a bearer key; keeping it on disk is what makes the
4
+ //! Bitwarden side password-free, exactly like the vault's own `never` mode.
5
+ //! It is never printed unless `bw-session get` is asked for it.
6
+
7
+ use std::fs;
8
+ use std::os::unix::fs::PermissionsExt;
9
+
10
+ use serde::{Deserialize, Serialize};
11
+
12
+ use crate::config::{self, UnlockMode};
13
+ use crate::crypto;
14
+ use crate::paths::Paths;
15
+ use crate::session::now_ms;
16
+
17
+ #[derive(Debug, Clone, Serialize, Deserialize)]
18
+ pub struct Stored {
19
+ #[serde(rename = "savedAt")]
20
+ pub saved_at: i64,
21
+ #[serde(default, skip_serializing_if = "Option::is_none", rename = "expiresAt")]
22
+ pub expires_at: Option<i64>,
23
+ pub key: String,
24
+ }
25
+
26
+ impl Stored {
27
+ pub fn expired(&self, now: i64) -> bool {
28
+ self.expires_at.is_some_and(|deadline| now >= deadline)
29
+ }
30
+ }
31
+
32
+ /// Store a key, honouring the current `bitwarden.unlock` policy. `session`
33
+ /// means "do not persist": the caller keeps it in memory instead.
34
+ pub fn save(paths: &Paths, key: &str) -> Result<Option<i64>, String> {
35
+ let policy = config::load(paths).bitwarden;
36
+ if policy.mode_is_session() {
37
+ clear(paths);
38
+ return Err("bitwarden.unlock is \"session\": the key is kept in the agent, not on disk".into());
39
+ }
40
+ let now = now_ms();
41
+ let expires_at = match policy.unlock {
42
+ UnlockMode::Never => None,
43
+ UnlockMode::Time => Some(now + policy.hours.clamp(1, 24 * 90) * 3_600_000),
44
+ UnlockMode::Session => None,
45
+ };
46
+ let stored = Stored { saved_at: now, expires_at, key: key.to_string() };
47
+ let bytes = serde_json::to_vec(&stored).map_err(|e| format!("cannot serialize session: {e}"))?;
48
+ crypto::write_atomic(&paths.bw_session(), &bytes)?;
49
+ let _ = fs::set_permissions(paths.bw_session(), fs::Permissions::from_mode(0o600));
50
+ Ok(expires_at)
51
+ }
52
+
53
+ pub fn load(paths: &Paths) -> Result<Option<Stored>, String> {
54
+ let path = paths.bw_session();
55
+ let text = match fs::read_to_string(&path) {
56
+ Ok(text) => text,
57
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
58
+ Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
59
+ };
60
+ let stored: Stored = match serde_json::from_str(&text) {
61
+ Ok(stored) => stored,
62
+ Err(_) => {
63
+ let _ = fs::remove_file(&path);
64
+ return Ok(None);
65
+ }
66
+ };
67
+ if stored.expired(now_ms()) {
68
+ let _ = fs::remove_file(&path);
69
+ return Ok(None);
70
+ }
71
+ Ok(Some(stored))
72
+ }
73
+
74
+ pub fn clear(paths: &Paths) -> bool {
75
+ fs::remove_file(paths.bw_session()).is_ok()
76
+ }
77
+
78
+ impl config::BitwardenPolicy {
79
+ pub fn mode_is_session(&self) -> bool {
80
+ self.unlock == UnlockMode::Session
81
+ }
82
+ }
@@ -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::config::{self, UnlockMode, UnlockPolicy};
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"
@@ -285,6 +302,10 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
285
302
  Cmd::Unlock { password_stdin, requester, idle_min } => {
286
303
  unlock(paths, &out, password_stdin, &requester, idle_min)
287
304
  }
305
+ Cmd::Settings { key, value, password_stdin } => {
306
+ settings(paths, &out, key.as_deref(), value.as_deref(), None, password_stdin)
307
+ }
308
+ Cmd::BwSession { action } => bw_session(paths, &out, &action),
288
309
  Cmd::Mode { action, value, hours, password_stdin } => {
289
310
  mode(paths, &out, &action, value.as_deref(), hours, password_stdin)
290
311
  }
@@ -610,85 +631,213 @@ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_
610
631
  Ok(())
611
632
  }
612
633
 
613
- /// Show or change the password policy. Changing it always costs the master
614
- /// password: `never` writes the key to disk, so it must not be a drive-by act.
615
- fn mode(
634
+ /// Dotted setting names, with the aliases a human is likely to type.
635
+ fn setting_key(raw: &str) -> Option<&'static str> {
636
+ match raw.trim().to_lowercase().as_str() {
637
+ "vault.unlock" | "vault.mode" | "unlock" | "mode" => Some("vault.unlock"),
638
+ "vault.hours" | "hours" => Some("vault.hours"),
639
+ "bitwarden.unlock" | "bitwarden.mode" | "bw.unlock" | "bw.mode" => Some("bitwarden.unlock"),
640
+ "bitwarden.hours" | "bw.hours" => Some("bitwarden.hours"),
641
+ "bitwarden.import" | "bw.import" | "import" => Some("bitwarden.import"),
642
+ _ => None,
643
+ }
644
+ }
645
+
646
+ fn settings_value(config: &config::Config, paths: &Paths) -> serde_json::Value {
647
+ let bw_saved = bwsession::load(paths).ok().flatten();
648
+ json!({
649
+ "ok": true,
650
+ "vault": {
651
+ "unlock": config.unlock.mode.as_str(),
652
+ "hours": config.unlock.hours,
653
+ "auto": paths.auto_session().exists(),
654
+ },
655
+ "bitwarden": {
656
+ "unlock": config.bitwarden.unlock.as_str(),
657
+ "hours": config.bitwarden.hours,
658
+ "import": config.bitwarden.import.as_str(),
659
+ "persisted": bw_saved.is_some(),
660
+ "expiresAt": bw_saved.as_ref().and_then(|s| s.expires_at),
661
+ },
662
+ })
663
+ }
664
+
665
+ fn settings_human(config: &config::Config, paths: &Paths) -> String {
666
+ [
667
+ format!("vault.unlock: {} (never | time | session)", config.unlock.mode.as_str()),
668
+ format!("vault.hours: {} (time 模式)", config.unlock.hours),
669
+ format!(
670
+ "vault 机器级会话: {}",
671
+ if paths.auto_session().exists() { "有(免密)" } else { "无" }
672
+ ),
673
+ format!("bitwarden.unlock: {} (never | time | session)", config.bitwarden.unlock.as_str()),
674
+ format!("bitwarden.hours: {}", config.bitwarden.hours),
675
+ format!("bitwarden.import: {} (ask | always | never)", config.bitwarden.import.as_str()),
676
+ format!(
677
+ "bitwarden 已落盘的会话: {}",
678
+ match bwsession::load(paths).ok().flatten() {
679
+ Some(saved) => match saved.expires_at {
680
+ Some(at) => format!("有({} 后过期)", ((at - session::now_ms()) / 60_000).max(0)),
681
+ None => "有(不过期)".to_string(),
682
+ },
683
+ None => "无".to_string(),
684
+ }
685
+ ),
686
+ ]
687
+ .join("\n")
688
+ }
689
+
690
+ fn settings(
616
691
  paths: &Paths,
617
692
  out: &Out,
618
- action: &str,
693
+ key: Option<&str>,
619
694
  value: Option<&str>,
620
695
  hours: Option<i64>,
621
696
  password_stdin: bool,
622
697
  ) -> Outcome {
623
- match action.trim() {
624
- "" | "get" | "status" => {
625
- let policy = config::load(paths).unlock;
626
- let auto = paths.auto_session().exists();
627
- out.value(
628
- json!({
629
- "ok": true,
630
- "mode": policy.mode.as_str(),
631
- "hours": policy.hours,
632
- "auto": auto,
633
- "store": paths.store(),
634
- }),
635
- || {
636
- format!(
637
- "mode: {}\nhours: {}\nmachine-wide session: {}",
638
- policy.mode.as_str(),
639
- policy.hours,
640
- if auto { "yes (no password needed)" } else { "no" }
641
- )
642
- },
643
- );
644
- Ok(())
645
- }
646
- "set" => {
647
- let value = value.ok_or_else(|| {
648
- Fault::Usage("usage: ai-vault mode set never|time|session [--hours N]".into())
649
- })?;
650
- let mode = UnlockMode::parse(value)
651
- .ok_or_else(|| Fault::Usage(format!("unknown mode \"{value}\" — use never, time or session")))?;
698
+ let mut config = config::load(paths);
699
+
700
+ let Some(raw_key) = key.filter(|k| !k.trim().is_empty()) else {
701
+ let value = settings_value(&config, paths);
702
+ out.value(value, || settings_human(&config, paths));
703
+ return Ok(());
704
+ };
705
+ let key = setting_key(raw_key).ok_or_else(|| {
706
+ Fault::Usage(format!(
707
+ "unknown setting \"{raw_key}\" — vault.unlock, vault.hours, bitwarden.unlock, bitwarden.hours, bitwarden.import"
708
+ ))
709
+ })?;
710
+
711
+ let Some(raw_value) = value.map(str::trim).filter(|v| !v.is_empty()) else {
712
+ let shown = match key {
713
+ "vault.unlock" => config.unlock.mode.as_str().to_string(),
714
+ "vault.hours" => config.unlock.hours.to_string(),
715
+ "bitwarden.unlock" => config.bitwarden.unlock.as_str().to_string(),
716
+ "bitwarden.hours" => config.bitwarden.hours.to_string(),
717
+ _ => config.bitwarden.import.as_str().to_string(),
718
+ };
719
+ out.value(json!({ "ok": true, "key": key, "value": shown }), || format!("{key}: {shown}"));
720
+ return Ok(());
721
+ };
722
+
723
+ match key {
724
+ "vault.unlock" => {
725
+ let mode = UnlockMode::parse(raw_value)
726
+ .ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
652
727
  let store = open_store(paths)?;
728
+ // Changing when the vault opens is a security decision: always verify.
653
729
  let password = if password_stdin {
654
730
  read_password()?
655
731
  } else {
656
732
  ask_password("ai-vault · 主密码", "切换解锁模式")?
657
733
  };
658
- let (_, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
734
+ let (_, vault_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
659
735
  crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
660
736
  crypto::OpenError::Broken(message) => Fault::Error(message),
661
737
  })?;
662
- let hours = hours.unwrap_or(config::load(paths).unlock.hours).clamp(1, 24 * 90);
663
- config::save(paths, &config::Config { unlock: UnlockPolicy { mode, hours } })?;
738
+ config.unlock = UnlockPolicy { mode, hours: hours.unwrap_or(config.unlock.hours).clamp(1, 24 * 90) };
739
+ config::save(paths, &config)?;
664
740
  session::ensure_session_dir(paths)?;
665
- let auto = if mode == UnlockMode::Never {
666
- let session = Session::new("mode", 0, None, &store, &key);
667
- session::save_auto(paths, &session)?;
668
- true
741
+ if mode == UnlockMode::Never {
742
+ let auto = Session::new("mode", 0, None, &store, &vault_key);
743
+ session::save_auto(paths, &auto)?;
669
744
  } else {
670
745
  session::delete_auto(paths);
671
- false
672
- };
746
+ }
673
747
  audit::append(&paths.audit(), "cli", "mode", None, Some(mode.as_str()));
674
- let warn = if mode == UnlockMode::Never {
675
- "\n注意: 密钥已写到磁盘(0600)。任何能读你文件的程序/人都能读出库里的密码。"
676
- } else {
677
- ""
678
- };
748
+ }
749
+ "vault.hours" => {
750
+ let hours: i64 = raw_value
751
+ .parse()
752
+ .map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
753
+ config.unlock.hours = hours.clamp(1, 24 * 90);
754
+ config::save(paths, &config)?;
755
+ }
756
+ "bitwarden.unlock" => {
757
+ let mode = UnlockMode::parse(raw_value)
758
+ .ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
759
+ config.bitwarden.unlock = mode;
760
+ if let Some(hours) = hours {
761
+ config.bitwarden.hours = hours.clamp(1, 24 * 90);
762
+ }
763
+ config::save(paths, &config)?;
764
+ // Going back to per-session must not leave a key on disk.
765
+ if mode == UnlockMode::Session {
766
+ bwsession::clear(paths);
767
+ }
768
+ }
769
+ "bitwarden.hours" => {
770
+ let hours: i64 = raw_value
771
+ .parse()
772
+ .map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
773
+ config.bitwarden.hours = hours.clamp(1, 24 * 90);
774
+ config::save(paths, &config)?;
775
+ }
776
+ _ => {
777
+ let import = ImportPolicy::parse(raw_value).ok_or_else(|| {
778
+ Fault::Usage(format!("unknown import policy \"{raw_value}\" — ask, always or never"))
779
+ })?;
780
+ config.bitwarden.import = import;
781
+ config::save(paths, &config)?;
782
+ }
783
+ }
784
+
785
+ let value = settings_value(&config, paths);
786
+ out.value(value, || settings_human(&config, paths));
787
+ Ok(())
788
+ }
789
+
790
+ /// `/vault mode` is a shortcut for the `vault.unlock` setting.
791
+ fn mode(
792
+ paths: &Paths,
793
+ out: &Out,
794
+ action: &str,
795
+ value: Option<&str>,
796
+ hours: Option<i64>,
797
+ password_stdin: bool,
798
+ ) -> Outcome {
799
+ match action.trim() {
800
+ "" | "get" | "status" => settings(paths, out, Some("vault.unlock"), None, None, password_stdin),
801
+ "set" => settings(paths, out, Some("vault.unlock"), value, hours, password_stdin),
802
+ other => Err(Fault::Usage(format!("unknown mode action \"{other}\""))),
803
+ }
804
+ }
805
+
806
+ fn bw_session(paths: &Paths, out: &Out, action: &str) -> Outcome {
807
+ match action.trim() {
808
+ "" | "get" => {
809
+ let stored = bwsession::load(paths)?
810
+ .ok_or_else(|| Fault::Auth("no persisted Bitwarden session — unlock Bitwarden first".into()))?;
679
811
  out.value(
680
- json!({ "ok": true, "mode": mode.as_str(), "hours": hours, "auto": auto }),
681
- || {
682
- format!(
683
- "mode set to {}{}",
684
- mode.as_str(),
685
- if auto { " — no password needed from now on" } else { "" }
686
- ) + warn
687
- },
812
+ json!({ "ok": true, "key": stored.key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
813
+ || stored.key.clone(),
688
814
  );
689
815
  Ok(())
690
816
  }
691
- other => Err(Fault::Usage(format!("unknown mode action \"{other}\""))),
817
+ "put" | "save" => {
818
+ let key = read_stdin_text()?.trim().to_string();
819
+ if key.is_empty() {
820
+ return Err(Fault::Usage("bw-session put expects the session key on stdin".into()));
821
+ }
822
+ let expires_at = bwsession::save(paths, &key)?;
823
+ audit::append(&paths.audit(), "cli", "bw_session", None, Some("put"));
824
+ out.value(json!({ "ok": true, "expiresAt": expires_at }), || {
825
+ match expires_at {
826
+ Some(at) => format!("saved (expires in {} min)", ((at - session::now_ms()) / 60_000).max(0)),
827
+ None => "saved (no expiry)".to_string(),
828
+ }
829
+ });
830
+ Ok(())
831
+ }
832
+ "clear" | "delete" => {
833
+ let removed = bwsession::clear(paths);
834
+ audit::append(&paths.audit(), "cli", "bw_session", None, Some("clear"));
835
+ out.value(json!({ "ok": true, "removed": removed }), || {
836
+ if removed { "cleared".to_string() } else { "nothing stored".to_string() }
837
+ });
838
+ Ok(())
839
+ }
840
+ other => Err(Fault::Usage(format!("unknown bw-session action \"{other}\""))),
692
841
  }
693
842
  }
694
843
 
@@ -1,5 +1,9 @@
1
- //! Machine-wide unlock policy: how often the vault asks for the master
2
- //! password. Switching the mode always re-verifies the master password.
1
+ //! Machine-wide settings: when the vault asks for its master password, when
2
+ //! the Bitwarden side asks, and whether a Bitwarden hit may be imported
3
+ //! without asking.
4
+ //!
5
+ //! Stored in `<dir>/config.json` (0600, written atomically). A missing or
6
+ //! broken file means the defaults: ask once per session, offer imports.
3
7
 
4
8
  use serde::{Deserialize, Serialize};
5
9
  use std::fs;
@@ -38,6 +42,36 @@ impl UnlockMode {
38
42
  }
39
43
  }
40
44
 
45
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
46
+ #[serde(rename_all = "lowercase")]
47
+ pub enum ImportPolicy {
48
+ /// Show the Bitwarden hit, read it once, then ask whether to import it.
49
+ Ask,
50
+ /// Import whatever is found and hand it back: no window at all.
51
+ Always,
52
+ /// Never write a Bitwarden entry into the store; read one-offs only.
53
+ Never,
54
+ }
55
+
56
+ impl ImportPolicy {
57
+ pub fn parse(text: &str) -> Option<ImportPolicy> {
58
+ match text.trim().to_lowercase().as_str() {
59
+ "ask" | "confirm" => Some(ImportPolicy::Ask),
60
+ "always" | "auto" | "yes" => Some(ImportPolicy::Always),
61
+ "never" | "no" | "off" => Some(ImportPolicy::Never),
62
+ _ => None,
63
+ }
64
+ }
65
+
66
+ pub fn as_str(self) -> &'static str {
67
+ match self {
68
+ ImportPolicy::Ask => "ask",
69
+ ImportPolicy::Always => "always",
70
+ ImportPolicy::Never => "never",
71
+ }
72
+ }
73
+ }
74
+
41
75
  #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
42
76
  pub struct UnlockPolicy {
43
77
  pub mode: UnlockMode,
@@ -56,14 +90,43 @@ impl Default for UnlockPolicy {
56
90
  }
57
91
  }
58
92
 
59
- #[derive(Debug, Clone, Serialize, Deserialize, Default)]
93
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
94
+ pub struct BitwardenPolicy {
95
+ /// `never` keeps the `bw` session key in the store directory, so no
96
+ /// Bitwarden master password is asked; `time` does the same with a
97
+ /// deadline; `session` (default) keeps it in the agent's memory only.
98
+ #[serde(default = "default_bw_mode")]
99
+ pub unlock: UnlockMode,
100
+ #[serde(default = "default_hours")]
101
+ pub hours: i64,
102
+ #[serde(default = "default_import")]
103
+ pub import: ImportPolicy,
104
+ }
105
+
106
+ fn default_bw_mode() -> UnlockMode {
107
+ UnlockMode::Session
108
+ }
109
+
110
+ fn default_import() -> ImportPolicy {
111
+ ImportPolicy::Ask
112
+ }
113
+
114
+ impl Default for BitwardenPolicy {
115
+ fn default() -> Self {
116
+ BitwardenPolicy { unlock: default_bw_mode(), hours: default_hours(), import: default_import() }
117
+ }
118
+ }
119
+
120
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
60
121
  pub struct Config {
61
122
  #[serde(default)]
62
123
  pub unlock: UnlockPolicy,
124
+ #[serde(default)]
125
+ pub bitwarden: BitwardenPolicy,
63
126
  }
64
127
 
65
- /// A missing or unreadable config means the default policy: ask once per
66
- /// session. A broken file must not lock anyone out of their vault.
128
+ /// A missing or unreadable config means the defaults. A broken file must not
129
+ /// lock anyone out of their vault.
67
130
  pub fn load(paths: &Paths) -> Config {
68
131
  match fs::read_to_string(paths.config()) {
69
132
  Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
@@ -75,3 +138,34 @@ pub fn save(paths: &Paths, config: &Config) -> Result<(), String> {
75
138
  let bytes = serde_json::to_vec_pretty(config).map_err(|e| format!("cannot serialize config: {e}"))?;
76
139
  crypto::write_atomic(&paths.config(), &bytes)
77
140
  }
141
+
142
+ #[cfg(test)]
143
+ mod tests {
144
+ use super::*;
145
+
146
+ #[test]
147
+ fn parses_aliases() {
148
+ assert_eq!(UnlockMode::parse("no-password"), Some(UnlockMode::Never));
149
+ assert_eq!(UnlockMode::parse("SESSION"), Some(UnlockMode::Session));
150
+ assert_eq!(UnlockMode::parse("2h"), None);
151
+ assert_eq!(ImportPolicy::parse("auto"), Some(ImportPolicy::Always));
152
+ assert_eq!(ImportPolicy::parse("off"), Some(ImportPolicy::Never));
153
+ }
154
+
155
+ #[test]
156
+ fn defaults_are_the_cautious_ones() {
157
+ let config = Config::default();
158
+ assert_eq!(config.unlock.mode, UnlockMode::Session);
159
+ assert_eq!(config.bitwarden.unlock, UnlockMode::Session);
160
+ assert_eq!(config.bitwarden.import, ImportPolicy::Ask);
161
+ }
162
+
163
+ #[test]
164
+ fn old_configs_still_load() {
165
+ // A config written by the previous version had only `unlock`.
166
+ let parsed: Config = serde_json::from_str(r#"{"unlock":{"mode":"time","hours":4}}"#).unwrap();
167
+ assert_eq!(parsed.unlock.mode, UnlockMode::Time);
168
+ assert_eq!(parsed.bitwarden.import, ImportPolicy::Ask);
169
+ assert_eq!(parsed.bitwarden.hours, 8);
170
+ }
171
+ }
@@ -7,6 +7,7 @@
7
7
  //! token back on every later call.
8
8
 
9
9
  mod audit;
10
+ mod bwsession;
10
11
  mod cli;
11
12
  mod config;
12
13
  mod crypto;
@@ -42,6 +42,11 @@ impl Paths {
42
42
  self.dir.join("agent.session.json")
43
43
  }
44
44
 
45
+ /// The `bw` session key kept for `bitwarden.unlock = never | time`.
46
+ pub fn bw_session(&self) -> PathBuf {
47
+ self.dir.join("bitwarden.session.json")
48
+ }
49
+
45
50
  /// Shared advisory lock for read-modify-write of the store file.
46
51
  pub fn store_lock(&self) -> PathBuf {
47
52
  self.dir.join("store.lock")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaolikt/ai-vault",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable) plus the pi-ai-vault extension for pi and omp.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "access": "public"
34
34
  },
35
35
  "optionalDependencies": {
36
- "@xiaolikt/ai-vault-linux-x64": "0.5.0"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.6.0"
37
37
  },
38
38
  "files": [
39
39
  "bin",
@@ -51,7 +51,15 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
51
51
  | `time` | 解锁后 N 小时(默认 8)再问一次 |
52
52
  | `session` | 每个会话一次,会话结束失效(默认) |
53
53
 
54
- `vault_get` 找不到本地条目时会去 Bitwarden 搜;命中后先给你看这一条并问是否读取,读了再问「导入 ai-vault(以后免 Bitwarden)还是只用这一次」。所以 **只有你同意导入的密码才会进 ai-vault**。
54
+ `vault_get` 找不到本地条目时会去 Bitwarden 搜;命中后按 `bitwarden.import` 处理:
55
+
56
+ | `bitwarden.import` | 行为 |
57
+ |---|---|
58
+ | `ask`(默认) | 给你看这一条 → 读一次 → 问「导入 ai-vault / 只用这一次」 |
59
+ | `always` | 命中直接导入并返回,不开窗口 |
60
+ | `never` | 只读一次,永不写入本地库 |
61
+
62
+ 所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
55
63
 
56
64
  ## 隔离
57
65
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store plus live Bitwarden. Works in pi and in omp (the omp fork reads the same manifest).",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "security"
26
26
  ],
27
27
  "dependencies": {
28
- "@xiaolikt/ai-vault": "0.5.0"
28
+ "@xiaolikt/ai-vault": "0.6.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
@@ -55,6 +55,7 @@ import { Type } from "typebox";
55
55
  import { bitwardenLogins, filterLogins, type LoginDraft } from "./import-map.js";
56
56
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
57
57
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
58
+ import { getSettingsSafe, settingsCli } from "./settings.js";
58
59
  import { scrubDeep, scrubText } from "./scrub.js";
59
60
 
60
61
  // ---------------------------------------------------------------------------
@@ -492,6 +493,9 @@ function startAutoLock(st: BwState, ctx: ExtensionContext | undefined): void {
492
493
  /** Drop this binding's session key and injected variables, and the clipboard. */
493
494
  async function lock(st: BwState, reason: string): Promise<void> {
494
495
  const hadSession = !!st.key;
496
+ // A key kept for `bitwarden.unlock = never | time` must go with an explicit
497
+ // lock, or the next call would silently unlock again.
498
+ void settingsCli().run(["bw-session", "clear"]).catch(() => undefined);
495
499
  st.epoch++;
496
500
  st.key = undefined;
497
501
  st.verifiedAt = 0;
@@ -545,6 +549,27 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
545
549
 
546
550
  const epoch = st.epoch;
547
551
  const pending = (async () => {
552
+ const policy = (await getSettingsSafe(signal)).bitwarden;
553
+ // `never` / `time`: the CLI keeps the session key (0600, in the store
554
+ // directory), so Bitwarden costs no window at all.
555
+ if (policy.unlock !== "session") {
556
+ try {
557
+ const saved = await settingsCli().json<{ key: string }>(["bw-session", "get"], { signal });
558
+ if (saved?.key) {
559
+ const verify = await bwStatus(saved.key, signal);
560
+ if (verify?.status === "unlocked") {
561
+ st.key = saved.key;
562
+ st.verifiedAt = Date.now();
563
+ acquireSessionKey();
564
+ startAutoLock(st, ctx);
565
+ return saved.key;
566
+ }
567
+ }
568
+ } catch {
569
+ /* absent or expired: fall through to the password */
570
+ }
571
+ }
572
+
548
573
  const status = await bwStatus(undefined, signal); // no session env
549
574
  if (status?.status === "unauthenticated") throw new Error(BW_LOGIN_HINT);
550
575
 
@@ -569,6 +594,11 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
569
594
  st.verifiedAt = Date.now();
570
595
  acquireSessionKey();
571
596
  startAutoLock(st, ctx);
597
+ if (policy.unlock !== "session") {
598
+ // Keep the key where the CLI can hand it back; the file's expiry comes
599
+ // from the bitwarden.hours policy.
600
+ await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
601
+ }
572
602
  await audit("unlock", "ok", st.sessionLabel);
573
603
  // Refresh in the background: a full sync can take seconds on large vaults.
574
604
  const lastSync = Date.parse(status?.lastSync ?? "");
@@ -25,6 +25,7 @@ import {
25
25
  import { CliError, VaultCli } from "./cli.js";
26
26
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
27
27
  import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
28
+ import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
28
29
 
29
30
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
30
31
 
@@ -309,22 +310,21 @@ async function bitwardenFallback(
309
310
  }
310
311
  if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
311
312
 
312
- const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
313
- const allow = await confirmWindow(
314
- dialogs(ctx),
315
- "pi-ai-vault · Bitwarden 里找到",
316
- `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
317
- signal,
318
- );
319
- if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
313
+ const asValue = (via: string): ToolOutcome => ({
314
+ content: [
315
+ {
316
+ type: "text" as const,
317
+ text: JSON.stringify(
318
+ { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
319
+ null,
320
+ 1,
321
+ ),
322
+ },
323
+ ],
324
+ details: { item: hit.name, via },
325
+ });
320
326
 
321
- const importIt = await confirmWindow(
322
- dialogs(ctx),
323
- "pi-ai-vault · 导入到 ai-vault",
324
- `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
325
- signal,
326
- );
327
- if (importIt) {
327
+ const importIt = async (): Promise<ToolOutcome> => {
328
328
  try {
329
329
  const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
330
330
  stdin: JSON.stringify([
@@ -343,34 +343,32 @@ async function bitwardenFallback(
343
343
  } catch (error) {
344
344
  return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
345
345
  }
346
- return {
347
- content: [
348
- {
349
- type: "text" as const,
350
- text: JSON.stringify(
351
- { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "imported-from-bitwarden" },
352
- null,
353
- 1,
354
- ),
355
- },
356
- ],
357
- details: { item: hit.name, via: "imported-from-bitwarden" },
358
- };
346
+ return asValue("imported-from-bitwarden");
347
+ };
348
+
349
+ const policy = (await getSettingsSafe(signal)).bitwarden.import;
350
+ if (policy === "always") {
351
+ // bitwarden.import = always: the user opted into pulling hits in silently.
352
+ return importIt();
359
353
  }
360
354
 
361
- return {
362
- content: [
363
- {
364
- type: "text" as const,
365
- text: JSON.stringify(
366
- { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "bitwarden-once" },
367
- null,
368
- 1,
369
- ),
370
- },
371
- ],
372
- details: { item: hit.name, via: "bitwarden-once" },
373
- };
355
+ const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
356
+ const allow = await confirmWindow(
357
+ dialogs(ctx),
358
+ "pi-ai-vault · Bitwarden 里找到",
359
+ `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
360
+ signal,
361
+ );
362
+ if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
363
+ if (policy === "never") return asValue("bitwarden-once");
364
+
365
+ const confirmed = await confirmWindow(
366
+ dialogs(ctx),
367
+ "pi-ai-vault · 导入到 ai-vault",
368
+ `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
369
+ signal,
370
+ );
371
+ return confirmed ? importIt() : asValue("bitwarden-once");
374
372
  }
375
373
 
376
374
  function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
@@ -628,6 +626,7 @@ const HELP = [
628
626
  "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
629
627
  "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
630
628
  "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
629
+ "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.unlock、bitwarden.import …)",
631
630
  "/vault status 状态与授权剩余时间",
632
631
  "/vault list 本地条目元数据",
633
632
  "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
@@ -688,6 +687,23 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
688
687
  }
689
688
  }
690
689
 
690
+ function settingsText(s: Settings): string {
691
+ const persisted = s.bitwarden.persisted
692
+ ? s.bitwarden.expiresAt
693
+ ? `有(${Math.max(0, Math.round((s.bitwarden.expiresAt - Date.now()) / 60_000))} 分钟后过期)`
694
+ : "有(不过期)"
695
+ : "无";
696
+ return [
697
+ `vault.unlock: ${s.vault.unlock} (never | time | session)`,
698
+ `vault.hours: ${s.vault.hours} (time 模式用)`,
699
+ `vault 机器级会话: ${s.vault.auto ? "有(免密)" : "无"}`,
700
+ `bitwarden.unlock: ${s.bitwarden.unlock} (never | time | session)`,
701
+ `bitwarden.hours: ${s.bitwarden.hours}`,
702
+ `bitwarden.import: ${s.bitwarden.import} (ask | always | never)`,
703
+ `bitwarden 已落盘的会话: ${persisted}`,
704
+ ].join("\n");
705
+ }
706
+
691
707
  function commandHandler(scope: Scope, bw: BwState) {
692
708
  return async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
693
709
  const [sub = "status", ...rest] = words(args);
@@ -756,6 +772,33 @@ function commandHandler(scope: Scope, bw: BwState) {
756
772
  }
757
773
  return;
758
774
  }
775
+ case "settings": {
776
+ const [key, ...valueParts] = rest;
777
+ const value = valueParts.join(" ").trim();
778
+ try {
779
+ if (!key) {
780
+ note(ctx, settingsText(await cli.json<Settings>(["settings"])));
781
+ return;
782
+ }
783
+ if (!value) {
784
+ const one = await cli.json<{ key: string; value: string }>(["settings", key]);
785
+ note(ctx, `${one.key}: ${one.value}`);
786
+ return;
787
+ }
788
+ // `vault.unlock` opens its own password window (or answers
789
+ // needs-ui); the other keys do not prompt at all.
790
+ const run = await cli.withPassword(["settings", key, value], () =>
791
+ promptSecret(dialogs(ctx), "ai-vault · 主密码", "改变解锁模式需要验证"),
792
+ );
793
+ forgetSettings();
794
+ const updated = JSON.parse(run.stdout) as Settings;
795
+ if (key.startsWith("vault.")) await lockNow(scope);
796
+ note(ctx, settingsText(updated));
797
+ } catch (error) {
798
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
799
+ }
800
+ return;
801
+ }
759
802
  case "mode": {
760
803
  const [sub, hoursArg] = rest;
761
804
  if (!sub || sub === "get" || sub === "status") {
@@ -785,6 +828,7 @@ function commandHandler(scope: Scope, bw: BwState) {
785
828
  try {
786
829
  const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), "ai-vault · 主密码", "切换解锁模式"));
787
830
  const result = JSON.parse(run.stdout) as { mode: UnlockModeName; hours: number; auto: boolean };
831
+ forgetSettings();
788
832
  await lockNow(scope);
789
833
  scope.mode = result.mode;
790
834
  scope.auto = result.auto;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Machine-wide settings, owned by the CLI (`ai-vault settings`), read here.
3
+ *
4
+ * The vault decides when to ask for its password; the Bitwarden side decides
5
+ * separately whether its `bw` session key may live on disk, and whether a hit
6
+ * may be imported into the vault without a window.
7
+ */
8
+ import { VaultCli } from "./cli.js";
9
+
10
+ export type UnlockModeName = "never" | "time" | "session";
11
+ export type ImportPolicy = "ask" | "always" | "never";
12
+
13
+ export interface Settings {
14
+ vault: { unlock: UnlockModeName; hours: number; auto: boolean };
15
+ bitwarden: {
16
+ unlock: UnlockModeName;
17
+ hours: number;
18
+ import: ImportPolicy;
19
+ persisted: boolean;
20
+ expiresAt: number | null;
21
+ };
22
+ }
23
+
24
+ export const DEFAULT_SETTINGS: Settings = {
25
+ vault: { unlock: "session", hours: 8, auto: false },
26
+ bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
27
+ };
28
+
29
+ const cli = new VaultCli();
30
+ let cache: { at: number; value: Settings } | undefined;
31
+
32
+ /** The shared CLI client, for the pieces that read and write the settings. */
33
+ export function settingsCli(): VaultCli {
34
+ return cli;
35
+ }
36
+
37
+ /**
38
+ * Settings change rarely, so a short cache keeps a Bitwarden call from paying
39
+ * for the read. `/vault settings ...` drops it explicitly.
40
+ */
41
+ export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
42
+ if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
43
+ const value = await cli.json<Settings>(["settings"], { signal });
44
+ cache = { at: Date.now(), value };
45
+ return value;
46
+ }
47
+
48
+ /** For paths that must keep working when the CLI is missing: defaults instead. */
49
+ export async function getSettingsSafe(signal?: AbortSignal): Promise<Settings> {
50
+ try {
51
+ return await getSettings(signal);
52
+ } catch {
53
+ return DEFAULT_SETTINGS;
54
+ }
55
+ }
56
+
57
+ export function forgetSettings(): void {
58
+ cache = undefined;
59
+ }
package/test/cli.sh CHANGED
@@ -128,6 +128,27 @@ PY
128
128
  check "back to session mode" 0 bash -c "printf 'correct horse' | '$BIN' mode set session --password-stdin --json"
129
129
  check "session mode needs a token again" 5 "$BIN" status
130
130
 
131
+ echo "== settings =="
132
+ check "settings prints everything" 0 "$BIN" settings --json
133
+ check "set bitwarden.import" 0 "$BIN" settings bitwarden.import never --json
134
+ "$BIN" settings bitwarden.import --json >"$TMP/set1"
135
+ python3 - "$TMP/set1" <<'PY' && ok "the import policy was stored" || bad "the import policy was not stored"
136
+ import json,sys
137
+ assert json.load(open(sys.argv[1]))["value"] == "never"
138
+ PY
139
+ check "an unknown setting is a usage error" 2 "$BIN" settings nope.value 1
140
+ check "bw-session put is refused in session mode" 1 bash -c "printf 'K' | '$BIN' bw-session put"
141
+ check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
142
+ check "bw-session put stores the key" 0 bash -c "printf 'GOOD_SESSION' | '$BIN' bw-session put --json"
143
+ [[ "$(stat -c %a "$AI_VAULT_DIR/bitwarden.session.json")" == "600" ]] && ok "the bw session file is 0600" || bad "the bw session file is not 0600"
144
+ check "bw-session get returns it" 0 "$BIN" bw-session get --json
145
+ check "switch back to session" 0 "$BIN" settings bitwarden.unlock session --json
146
+ check "the stored key is gone" 5 "$BIN" bw-session get
147
+ check "bitwarden.unlock time keeps an expiry" 0 "$BIN" settings bitwarden.unlock time --json
148
+ check "bw-session put in time mode" 0 bash -c "printf 'K2' | '$BIN' bw-session put --json"
149
+ grep -q '"expiresAt": *[0-9]' "$AI_VAULT_DIR/bitwarden.session.json" && ok "time mode writes a deadline" || bad "time mode wrote no deadline"
150
+ "$BIN" settings bitwarden.unlock session --json >/dev/null
151
+
131
152
  echo "== doctor =="
132
153
  check "doctor runs" 0 "$BIN" doctor --json
133
154
 
@@ -9,6 +9,7 @@ import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, subCtx, textOf, use
9
9
  // by `npm test`) plus the mock zenity, with a throwaway store.
10
10
  const dir = useMocks();
11
11
  const { default: aiVault } = await import("../packages/pi-ai-vault/src/index.ts");
12
+ const { forgetSettings } = await import("../packages/pi-ai-vault/src/settings.ts");
12
13
  cleanUpOnExit(dir);
13
14
 
14
15
  const PW = "correct horse battery";
@@ -215,3 +216,67 @@ test("never mode reads without any window, and the switch needs the password", a
215
216
  const back = switchMode("session");
216
217
  assert.equal(back.status, 0, back.stderr);
217
218
  });
219
+
220
+ test("bitwarden.import=never reads once with a single window", async () => {
221
+ const bin = process.env.AI_VAULT_BIN;
222
+ spawnSync(bin, ["settings", "bitwarden.import", "never"], { env: process.env });
223
+ forgetSettings();
224
+ const b = bind(aiVault, true);
225
+ const ctx = makeCtx().ctx;
226
+ answers.master(dir, PW);
227
+ await b.cmd("unlock", ctx);
228
+ answers.master(dir, "testmaster");
229
+ const before = prompts("--question");
230
+ answers.questions(dir, "y");
231
+ const result = await b.tool("vault_get", { name: "OtherService" }, ctx);
232
+ assert.equal(result.details.via, "bitwarden-once");
233
+ assert.equal(prompts("--question"), before + 1, "never: read approval only, no import question");
234
+ });
235
+
236
+ test("bitwarden.import=always pulls the entry in without a window", async () => {
237
+ const bin = process.env.AI_VAULT_BIN;
238
+ spawnSync(bin, ["settings", "bitwarden.import", "always"], { env: process.env });
239
+ forgetSettings();
240
+ const b = bind(aiVault, true);
241
+ const ctx = makeCtx().ctx;
242
+ answers.master(dir, PW);
243
+ await b.cmd("unlock", ctx);
244
+ answers.master(dir, "testmaster");
245
+ const before = prompts("--question");
246
+ const result = await b.tool("vault_get", { name: "OtherService" }, ctx);
247
+ assert.equal(result.details.via, "imported-from-bitwarden");
248
+ assert.equal(prompts("--question"), before, "always: no window at all");
249
+
250
+ answers.master(dir, PW);
251
+ const listed = await b.tool("vault_list", {}, ctx);
252
+ assert.equal(
253
+ JSON.parse(textOf(listed)).some((i) => i.name === "OtherService"),
254
+ true,
255
+ );
256
+ spawnSync(bin, ["settings", "bitwarden.import", "ask"], { env: process.env });
257
+ forgetSettings();
258
+ });
259
+
260
+ test("a persisted Bitwarden session costs no password", async () => {
261
+ const bin = process.env.AI_VAULT_BIN;
262
+ const set = (key, value) => spawnSync(bin, ["settings", key, value], { env: process.env, encoding: "utf8" });
263
+ assert.equal(set("bitwarden.unlock", "never").status, 0);
264
+ forgetSettings();
265
+ const put = spawnSync(bin, ["bw-session", "put"], { input: "GOOD_SESSION", env: process.env, encoding: "utf8" });
266
+ assert.equal(put.status, 0, put.stderr);
267
+
268
+ const b = bind(aiVault, true);
269
+ const ctx = makeCtx().ctx;
270
+ answers.master(dir, PW);
271
+ answers.master(dir, PW); // would be consumed only by a Bitwarden prompt
272
+ const before = prompts("--password");
273
+ const listed = await b.tool("bw_list", {}, ctx);
274
+ assert.equal(listed.isError, undefined);
275
+ assert.equal(prompts("--password"), before, "the stored bw session must be used silently");
276
+
277
+ // Restoring the session policy drops the key from disk.
278
+ assert.equal(set("bitwarden.unlock", "session").status, 0);
279
+ forgetSettings();
280
+ const get = spawnSync(bin, ["bw-session", "get"], { env: process.env, encoding: "utf8" });
281
+ assert.equal(get.status, 5, "switching back to session must remove the stored key");
282
+ });