@xiaolikt/ai-vault 0.8.0 → 0.9.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.8.0"
17
+ version = "0.9.0"
18
18
  dependencies = [
19
19
  "base64",
20
20
  "chacha20poly1305",
package/README.md CHANGED
@@ -93,8 +93,9 @@ 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` |
96
+ | `settings [键] [值]` | 全部设置:`vault.*` `bitwarden.*` `ente.unlock` `ente.hours` |
97
97
  | `bw-session get\|put\|clear` | Bitwarden 会话密钥的落盘副本(`bitwarden.unlock != session` 时用,加密封存) |
98
+ | `ente-session get\|put\|clear` | Ente 的 `ENTE_CLI_VAULT_KEY`(`ente.unlock != session` 时用,同样加密封存) |
98
99
  | `rekey` | 把旧库的 scrypt 参数升到当前默认(要主密码) |
99
100
  | `status --token T` | 条目数、过期时间、还活着的读授权 |
100
101
  | `lock --token T \| --all` | 丢掉令牌(`--all` 清空本机所有会话) |
@@ -149,6 +150,8 @@ ai-vault get <条目> --token <T> --answer-stdin --approval <hex> <<< 'y'
149
150
  | `ente_list` | Ente Auth 条目元数据(名称/签发方/账号/类型) | read | 否 |
150
151
  | `ente_code` | 读一条当前 TOTP/Steam 验证码,每次弹窗确认 | write | 是,用户当场允许 |
151
152
 
153
+ Ente 的会话由 `ente` 自己管(登录一次);`ente.unlock` 只决定那把 `ENTE_CLI_VAULT_KEY` 要不要由 ai-vault 加密封存。
154
+
152
155
  字段选择:`password`(默认)· `totp`(种子)· `code`(动态验证码)· `notes` · `field:<自定义字段名>`。
153
156
 
154
157
  ### 查询顺序:本地优先,Bitwarden 兜底
@@ -264,6 +267,15 @@ export ENTE_CLI_VAULT_KEY=<那个 key> # 之后连钥匙串都不用
264
267
 
265
268
  所以在 `session` 这种日常形态下,**每次查看不会再要你的密码**,最多要一次系统钥匙串解锁。
266
269
 
270
+ 想连钥匙串都不要(无人值守):
271
+
272
+ ```bash
273
+ ente vault key generate # 打印一个 key,拿一次就固定
274
+ /vault ente-key # 在弹窗里粘进去,ai-vault 把它加密封存
275
+ /vault settings ente.unlock never # 之后 ente 子进程自动带上它
276
+ ```
277
+ `ente.unlock` 和 `bitwarden.unlock` 是同一套三档(`never`/`time`/`session`),`ente-session get|put|clear` 是它的 CLI 入口;密钥用库目录的 wrap key 封存(0600),单独拷走 `ente.session.json` 解不开。插件永远不会把你 shell 里导出的 `ENTE_CLI_VAULT_KEY` 传给子进程——只有它自己封存的那把会。
278
+
267
279
  pi-ai-vault 只是这套 CLI 的客户端,本身不保存 Ente 的任何密钥:
268
280
 
269
281
  | 工具 | 作用 |
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ai-vault"
3
- version = "0.8.0"
3
+ version = "0.9.0"
4
4
  edition = "2021"
5
5
  description = "Machine-wide encrypted secret store shared by AI coding agents"
6
6
  license = "MIT"
@@ -9,7 +9,7 @@ use std::path::PathBuf;
9
9
  use clap::{Parser, Subcommand};
10
10
  use serde_json::json;
11
11
 
12
- use crate::bwsession;
12
+ use crate::sealed::{self, Kind};
13
13
  use crate::config::{self, ImportPolicy, UnlockMode, UnlockPolicy};
14
14
  use crate::crypto::{self, Kdf};
15
15
  use crate::dialog::{self, Answer};
@@ -84,6 +84,11 @@ enum Cmd {
84
84
  /// get | put | clear
85
85
  action: String,
86
86
  },
87
+ /// Ente's `ENTE_CLI_VAULT_KEY` (ente.unlock = never | time)
88
+ EnteSession {
89
+ /// get | put | clear
90
+ action: String,
91
+ },
87
92
  /// Show or change how often the master password is asked for
88
93
  Mode {
89
94
  /// "get" or "set"
@@ -321,7 +326,8 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
321
326
  Cmd::Settings { key, value, password_stdin } => {
322
327
  settings(paths, &out, key.as_deref(), value.as_deref(), None, password_stdin)
323
328
  }
324
- Cmd::BwSession { action } => bw_session(paths, &out, &action),
329
+ Cmd::BwSession { action } => sealed_session(paths, &out, Kind::Bitwarden, &action),
330
+ Cmd::EnteSession { action } => sealed_session(paths, &out, Kind::Ente, &action),
325
331
  Cmd::Mode { action, value, hours, password_stdin } => {
326
332
  mode(paths, &out, &action, value.as_deref(), hours, password_stdin)
327
333
  }
@@ -488,7 +494,7 @@ fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
488
494
  if let Some(secret) = host_secret() {
489
495
  return Ok(Some(secret));
490
496
  }
491
- bwsession::wrap_key_hex(paths).map(Some)
497
+ sealed::wrap_key_hex(paths).map(Some)
492
498
  }
493
499
 
494
500
  /// The host integration (the extension) is recognised by the secret it
@@ -496,6 +502,13 @@ fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
496
502
  /// and is treated like a human caller until it has a secret to sign with.
497
503
  /// This keeps a half-configured host from getting a session it can neither
498
504
  /// verify nor relay for.
505
+ fn kind_label(kind: Kind) -> &'static str {
506
+ match kind {
507
+ Kind::Bitwarden => "bitwarden",
508
+ Kind::Ente => "ente",
509
+ }
510
+ }
511
+
499
512
  fn is_host() -> bool {
500
513
  std::env::var_os("AI_VAULT_HOST").is_some_and(|v| v == "1") && host_secret().is_some()
501
514
  }
@@ -749,12 +762,15 @@ fn setting_key(raw: &str) -> Option<&'static str> {
749
762
  "bitwarden.unlock" | "bitwarden.mode" | "bw.unlock" | "bw.mode" => Some("bitwarden.unlock"),
750
763
  "bitwarden.hours" | "bw.hours" => Some("bitwarden.hours"),
751
764
  "bitwarden.import" | "bw.import" | "import" => Some("bitwarden.import"),
765
+ "ente.unlock" | "ente.mode" => Some("ente.unlock"),
766
+ "ente.hours" => Some("ente.hours"),
752
767
  _ => None,
753
768
  }
754
769
  }
755
770
 
756
771
  fn settings_value(config: &config::Config, paths: &Paths) -> serde_json::Value {
757
- let bw_saved = bwsession::load(paths).ok().flatten();
772
+ let bw_saved = sealed::load(paths, Kind::Bitwarden).ok().flatten();
773
+ let ente_saved = sealed::load(paths, Kind::Ente).ok().flatten();
758
774
  json!({
759
775
  "ok": true,
760
776
  "vault": {
@@ -763,12 +779,18 @@ fn settings_value(config: &config::Config, paths: &Paths) -> serde_json::Value {
763
779
  "auto": paths.auto_session().exists(),
764
780
  },
765
781
  "bitwarden": {
766
- "unlock": config.bitwarden.unlock.as_str(),
767
- "hours": config.bitwarden.hours,
782
+ "unlock": config.bitwarden.store.unlock.as_str(),
783
+ "hours": config.bitwarden.store.hours,
768
784
  "import": config.bitwarden.import.as_str(),
769
785
  "persisted": bw_saved.is_some(),
770
786
  "expiresAt": bw_saved.as_ref().and_then(|s| s.expires_at),
771
787
  },
788
+ "ente": {
789
+ "unlock": config.ente.unlock.as_str(),
790
+ "hours": config.ente.hours,
791
+ "persisted": ente_saved.is_some(),
792
+ "expiresAt": ente_saved.as_ref().and_then(|s| s.expires_at),
793
+ },
772
794
  })
773
795
  }
774
796
 
@@ -780,12 +802,15 @@ fn settings_human(config: &config::Config, paths: &Paths) -> String {
780
802
  "vault 机器级会话: {}",
781
803
  if paths.auto_session().exists() { "有(免密)" } else { "无" }
782
804
  ),
783
- format!("bitwarden.unlock: {} (never | time | session)", config.bitwarden.unlock.as_str()),
784
- format!("bitwarden.hours: {}", config.bitwarden.hours),
805
+ format!("bitwarden.unlock: {} (never | time | session)", config.bitwarden.store.unlock.as_str()),
806
+ format!("bitwarden.hours: {}", config.bitwarden.store.hours),
785
807
  format!("bitwarden.import: {} (ask | always | never)", config.bitwarden.import.as_str()),
808
+ format!("ente.unlock: {} (never | time | session)", config.ente.unlock.as_str()),
809
+ format!("ente.hours: {}", config.ente.hours),
810
+ format!("ente 已落盘的密钥: {}", if sealed::load(paths, Kind::Ente).ok().flatten().is_some() { "有" } else { "无" }),
786
811
  format!(
787
812
  "bitwarden 已落盘的会话: {}",
788
- match bwsession::load(paths).ok().flatten() {
813
+ match sealed::load(paths, Kind::Bitwarden).ok().flatten() {
789
814
  Some(saved) => match saved.expires_at {
790
815
  Some(at) => format!("有({} 后过期)", ((at - session::now_ms()) / 60_000).max(0)),
791
816
  None => "有(不过期)".to_string(),
@@ -822,8 +847,10 @@ fn settings(
822
847
  let shown = match key {
823
848
  "vault.unlock" => config.unlock.mode.as_str().to_string(),
824
849
  "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(),
850
+ "bitwarden.unlock" => config.bitwarden.store.unlock.as_str().to_string(),
851
+ "bitwarden.hours" => config.bitwarden.store.hours.to_string(),
852
+ "ente.unlock" => config.ente.unlock.as_str().to_string(),
853
+ "ente.hours" => config.ente.hours.to_string(),
827
854
  _ => config.bitwarden.import.as_str().to_string(),
828
855
  };
829
856
  out.value(json!({ "ok": true, "key": key, "value": shown }), || format!("{key}: {shown}"));
@@ -866,21 +893,40 @@ fn settings(
866
893
  "bitwarden.unlock" => {
867
894
  let mode = UnlockMode::parse(raw_value)
868
895
  .ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
869
- config.bitwarden.unlock = mode;
896
+ config.bitwarden.store.unlock = mode;
870
897
  if let Some(hours) = hours {
871
- config.bitwarden.hours = hours.clamp(1, 24 * 90);
898
+ config.bitwarden.store.hours = hours.clamp(1, 24 * 90);
872
899
  }
873
900
  config::save(paths, &config)?;
874
901
  // Going back to per-session must not leave a key on disk.
875
902
  if mode == UnlockMode::Session {
876
- bwsession::clear(paths);
903
+ sealed::clear(paths, Kind::Bitwarden);
877
904
  }
878
905
  }
879
906
  "bitwarden.hours" => {
880
907
  let hours: i64 = raw_value
881
908
  .parse()
882
909
  .map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
883
- config.bitwarden.hours = hours.clamp(1, 24 * 90);
910
+ config.bitwarden.store.hours = hours.clamp(1, 24 * 90);
911
+ config::save(paths, &config)?;
912
+ }
913
+ "ente.unlock" => {
914
+ let mode = UnlockMode::parse(raw_value)
915
+ .ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
916
+ config.ente.unlock = mode;
917
+ if let Some(hours) = hours {
918
+ config.ente.hours = hours.clamp(1, 24 * 90);
919
+ }
920
+ config::save(paths, &config)?;
921
+ if mode == UnlockMode::Session {
922
+ sealed::clear(paths, Kind::Ente);
923
+ }
924
+ }
925
+ "ente.hours" => {
926
+ let hours: i64 = raw_value
927
+ .parse()
928
+ .map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
929
+ config.ente.hours = hours.clamp(1, 24 * 90);
884
930
  config::save(paths, &config)?;
885
931
  }
886
932
  _ => {
@@ -913,12 +959,13 @@ fn mode(
913
959
  }
914
960
  }
915
961
 
916
- fn bw_session(paths: &Paths, out: &Out, action: &str) -> Outcome {
962
+ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome {
917
963
  match action.trim() {
918
964
  "" | "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()))?;
965
+ let stored = sealed::load(paths, kind)?
966
+ .ok_or_else(|| Fault::Auth(format!("no persisted {} secret — save one first", kind_label(kind))))?;
967
+ let key = sealed::key(paths, kind)?
968
+ .ok_or_else(|| Fault::Auth(format!("no persisted {} secret", kind_label(kind))))?;
922
969
  out.value(
923
970
  json!({ "ok": true, "key": key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
924
971
  || key,
@@ -930,8 +977,8 @@ fn bw_session(paths: &Paths, out: &Out, action: &str) -> Outcome {
930
977
  if key.is_empty() {
931
978
  return Err(Fault::Usage("bw-session put expects the session key on stdin".into()));
932
979
  }
933
- let expires_at = bwsession::save(paths, &key)?;
934
- audit::append(&paths.audit(), "cli", "bw_session", None, Some("put"));
980
+ let expires_at = sealed::save(paths, kind, &key)?;
981
+ audit::append(&paths.audit(), "cli", "sealed", None, Some(kind_label(kind)));
935
982
  out.value(json!({ "ok": true, "expiresAt": expires_at }), || {
936
983
  match expires_at {
937
984
  Some(at) => format!("saved (expires in {} min)", ((at - session::now_ms()) / 60_000).max(0)),
@@ -941,14 +988,14 @@ fn bw_session(paths: &Paths, out: &Out, action: &str) -> Outcome {
941
988
  Ok(())
942
989
  }
943
990
  "clear" | "delete" => {
944
- let removed = bwsession::clear(paths);
945
- audit::append(&paths.audit(), "cli", "bw_session", None, Some("clear"));
991
+ let removed = sealed::clear(paths, kind);
992
+ audit::append(&paths.audit(), "cli", "sealed", None, Some(kind_label(kind)));
946
993
  out.value(json!({ "ok": true, "removed": removed }), || {
947
994
  if removed { "cleared".to_string() } else { "nothing stored".to_string() }
948
995
  });
949
996
  Ok(())
950
997
  }
951
- other => Err(Fault::Usage(format!("unknown bw-session action \"{other}\""))),
998
+ other => Err(Fault::Usage(format!("unknown session action \"{other}\" (get, put, clear)"))),
952
999
  }
953
1000
  }
954
1001
 
@@ -90,15 +90,28 @@ impl Default for UnlockPolicy {
90
90
  }
91
91
  }
92
92
 
93
+ /// How a third-party CLI's credential is kept on disk.
93
94
  #[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.
95
+ pub struct StorePolicy {
96
+ /// `never` keeps the credential in the store directory (sealed), so the
97
+ /// CLI needs no keychain or password; `time` does the same with a
98
+ /// deadline; `session` (default) leaves it in the CLI's own keychain.
98
99
  #[serde(default = "default_bw_mode")]
99
100
  pub unlock: UnlockMode,
100
101
  #[serde(default = "default_hours")]
101
102
  pub hours: i64,
103
+ }
104
+
105
+ impl Default for StorePolicy {
106
+ fn default() -> Self {
107
+ StorePolicy { unlock: default_bw_mode(), hours: default_hours() }
108
+ }
109
+ }
110
+
111
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
112
+ pub struct BitwardenPolicy {
113
+ #[serde(flatten)]
114
+ pub store: StorePolicy,
102
115
  #[serde(default = "default_import")]
103
116
  pub import: ImportPolicy,
104
117
  }
@@ -113,7 +126,7 @@ fn default_import() -> ImportPolicy {
113
126
 
114
127
  impl Default for BitwardenPolicy {
115
128
  fn default() -> Self {
116
- BitwardenPolicy { unlock: default_bw_mode(), hours: default_hours(), import: default_import() }
129
+ BitwardenPolicy { store: StorePolicy::default(), import: default_import() }
117
130
  }
118
131
  }
119
132
 
@@ -123,6 +136,10 @@ pub struct Config {
123
136
  pub unlock: UnlockPolicy,
124
137
  #[serde(default)]
125
138
  pub bitwarden: BitwardenPolicy,
139
+ /// Ente's `ENTE_CLI_VAULT_KEY`: `session` leaves it to the OS keychain,
140
+ /// `never`/`time` keep it sealed next to the store.
141
+ #[serde(default)]
142
+ pub ente: StorePolicy,
126
143
  }
127
144
 
128
145
  /// A missing or unreadable config means the defaults. A broken file must not
@@ -156,7 +173,8 @@ mod tests {
156
173
  fn defaults_are_the_cautious_ones() {
157
174
  let config = Config::default();
158
175
  assert_eq!(config.unlock.mode, UnlockMode::Session);
159
- assert_eq!(config.bitwarden.unlock, UnlockMode::Session);
176
+ assert_eq!(config.bitwarden.store.unlock, UnlockMode::Session);
177
+ assert_eq!(config.ente.unlock, UnlockMode::Session);
160
178
  assert_eq!(config.bitwarden.import, ImportPolicy::Ask);
161
179
  }
162
180
 
@@ -166,6 +184,6 @@ mod tests {
166
184
  let parsed: Config = serde_json::from_str(r#"{"unlock":{"mode":"time","hours":4}}"#).unwrap();
167
185
  assert_eq!(parsed.unlock.mode, UnlockMode::Time);
168
186
  assert_eq!(parsed.bitwarden.import, ImportPolicy::Ask);
169
- assert_eq!(parsed.bitwarden.hours, 8);
187
+ assert_eq!(parsed.bitwarden.store.hours, 8);
170
188
  }
171
189
  }
@@ -7,7 +7,7 @@
7
7
  //! token back on every later call.
8
8
 
9
9
  mod audit;
10
- mod bwsession;
10
+ mod sealed;
11
11
  mod cli;
12
12
  mod config;
13
13
  mod crypto;
@@ -42,12 +42,6 @@ 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
- /// sealed under `wrap_key`.
47
- pub fn bw_session(&self) -> PathBuf {
48
- self.dir.join("bitwarden.session.json")
49
- }
50
-
51
45
  /// Random 256-bit key that seals the Bitwarden session at rest, so that
52
46
  /// file alone is not a bearer token. Same exposure as the store itself.
53
47
  pub fn wrap_key(&self) -> PathBuf {
@@ -1,4 +1,5 @@
1
- //! The `bw` session key, persisted for `bitwarden.unlock = never | time`.
1
+ //! Secrets kept on disk for `*.unlock = never | time`: the `bw` session key
2
+ //! and Ente's `ENTE_CLI_VAULT_KEY`.
2
3
  //!
3
4
  //! `bw unlock` hands back a bearer key for the *whole* Bitwarden vault, so the
4
5
  //! file is sealed: ChaCha20-Poly1305 under a random 256-bit key in
@@ -17,6 +18,30 @@ use crate::crypto;
17
18
  use crate::paths::Paths;
18
19
  use crate::session::now_ms;
19
20
 
21
+ /// Which secret this file holds. They are sealed the same way but carry
22
+ /// different names and different policies.
23
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
24
+ pub enum Kind {
25
+ Bitwarden,
26
+ Ente,
27
+ }
28
+
29
+ impl Kind {
30
+ fn file(self) -> &'static str {
31
+ match self {
32
+ Kind::Bitwarden => "bitwarden.session.json",
33
+ Kind::Ente => "ente.session.json",
34
+ }
35
+ }
36
+
37
+ fn policy(self, config: &config::Config) -> config::StorePolicy {
38
+ match self {
39
+ Kind::Bitwarden => config.bitwarden.store,
40
+ Kind::Ente => config.ente,
41
+ }
42
+ }
43
+ }
44
+
20
45
  #[derive(Debug, Clone, Serialize, Deserialize)]
21
46
  pub struct Stored {
22
47
  #[serde(rename = "savedAt")]
@@ -100,11 +125,18 @@ impl Stored {
100
125
 
101
126
  /// Store a key, honouring the current `bitwarden.unlock` policy. `session`
102
127
  /// means "do not persist": the caller keeps it in memory instead.
103
- pub fn save(paths: &Paths, key: &str) -> Result<Option<i64>, String> {
104
- let policy = config::load(paths).bitwarden;
105
- if policy.mode_is_session() {
106
- clear(paths);
107
- return Err("bitwarden.unlock is \"session\": the key is kept in the agent, not on disk".into());
128
+ pub fn save(paths: &Paths, kind: Kind, secret: &str) -> Result<Option<i64>, String> {
129
+ let config = config::load(paths);
130
+ let policy = kind.policy(&config);
131
+ if policy.unlock == UnlockMode::Session {
132
+ clear(paths, kind);
133
+ return Err(format!(
134
+ "{}.unlock is \"session\": nothing is kept on disk",
135
+ match kind {
136
+ Kind::Bitwarden => "bitwarden",
137
+ Kind::Ente => "ente",
138
+ }
139
+ ));
108
140
  }
109
141
  let now = now_ms();
110
142
  let expires_at = match policy.unlock {
@@ -113,15 +145,16 @@ pub fn save(paths: &Paths, key: &str) -> Result<Option<i64>, String> {
113
145
  UnlockMode::Session => None,
114
146
  };
115
147
  let wrap = wrap_key(paths)?;
116
- let stored = Stored { saved_at: now, expires_at, sealed: seal(&wrap, key)? };
148
+ let stored = Stored { saved_at: now, expires_at, sealed: seal(&wrap, secret)? };
117
149
  let bytes = serde_json::to_vec(&stored).map_err(|e| format!("cannot serialize session: {e}"))?;
118
- crypto::write_atomic(&paths.bw_session(), &bytes)?;
119
- let _ = fs::set_permissions(paths.bw_session(), fs::Permissions::from_mode(0o600));
150
+ let path = paths.dir.join(kind.file());
151
+ crypto::write_atomic(&path, &bytes)?;
152
+ let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
120
153
  Ok(expires_at)
121
154
  }
122
155
 
123
- pub fn load(paths: &Paths) -> Result<Option<Stored>, String> {
124
- let path = paths.bw_session();
156
+ pub fn load(paths: &Paths, kind: Kind) -> Result<Option<Stored>, String> {
157
+ let path = paths.dir.join(kind.file());
125
158
  let text = match fs::read_to_string(&path) {
126
159
  Ok(text) => text,
127
160
  Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
@@ -142,8 +175,8 @@ pub fn load(paths: &Paths) -> Result<Option<Stored>, String> {
142
175
  }
143
176
 
144
177
  /// The session key itself, or an error naming why it cannot be opened.
145
- pub fn key(paths: &Paths) -> Result<Option<String>, String> {
146
- match load(paths)? {
178
+ pub fn key(paths: &Paths, kind: Kind) -> Result<Option<String>, String> {
179
+ match load(paths, kind)? {
147
180
  None => Ok(None),
148
181
  Some(stored) => {
149
182
  let wrap = wrap_key(paths)?;
@@ -152,12 +185,6 @@ pub fn key(paths: &Paths) -> Result<Option<String>, String> {
152
185
  }
153
186
  }
154
187
 
155
- pub fn clear(paths: &Paths) -> bool {
156
- fs::remove_file(paths.bw_session()).is_ok()
157
- }
158
-
159
- impl config::BitwardenPolicy {
160
- pub fn mode_is_session(&self) -> bool {
161
- self.unlock == UnlockMode::Session
162
- }
188
+ pub fn clear(paths: &Paths, kind: Kind) -> bool {
189
+ fs::remove_file(paths.dir.join(kind.file())).is_ok()
163
190
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaolikt/ai-vault",
3
- "version": "0.8.0",
3
+ "version": "0.9.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.8.0"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.9.0"
37
37
  },
38
38
  "files": [
39
39
  "bin",
@@ -65,7 +65,9 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
65
65
 
66
66
  ## Ente
67
67
 
68
- `ente` CLI 自己登录一次(`ente account login --app auth`),插件只是它的客户端:`ente_list` 只给元数据,`ente_code` 每次弹窗确认。详见仓库 README。
68
+ `ente` CLI 自己登录一次(`ente account login --app auth`),插件只是它的客户端:`ente_list` 只给元数据,`ente_code` 每次弹窗确认。
69
+
70
+ 想完全免钥匙串:`ente vault key generate` → `/vault ente-key` 粘进去 → `/vault settings ente.unlock never`。密钥由 ai-vault 加密封存。详见仓库 README。
69
71
 
70
72
  ## 安全边界(一句话版)
71
73
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.8.0",
3
+ "version": "0.9.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.8.0"
28
+ "@xiaolikt/ai-vault": "0.9.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
@@ -25,6 +25,7 @@ import { Type } from "typebox";
25
25
  import { auditEvent } from "./bitwarden.js";
26
26
  import { confirmWindow, forDialog } from "./prompt.js";
27
27
  import { withTier } from "./host.js";
28
+ import { getSettingsSafe, settingsCli } from "./settings.js";
28
29
 
29
30
  export interface EnteCodeMeta {
30
31
  id: string;
@@ -74,12 +75,37 @@ interface Run {
74
75
  stderr: string;
75
76
  }
76
77
 
78
+ /**
79
+ * The environment for one `ente` run.
80
+ *
81
+ * `ente.unlock = never | time`: the key is kept sealed by ai-vault (the same
82
+ * wrapping as the Bitwarden session), so Ente needs neither the OS keychain
83
+ * nor a login window. `session` (default) leaves the keychain in charge and
84
+ * passes nothing.
85
+ */
86
+ async function enteEnv(signal?: AbortSignal): Promise<Record<string, string | undefined>> {
87
+ const env: Record<string, string | undefined> = { ...process.env };
88
+ // Never let a key the user exported in their shell decide this.
89
+ delete env.ENTE_CLI_VAULT_KEY;
90
+ const settings = await getSettingsSafe(signal);
91
+ if (settings.ente.unlock === "session") return env;
92
+ try {
93
+ const sealed = await settingsCli().json<{ key: string }>(["ente-session", "get"], { signal });
94
+ if (sealed?.key) env.ENTE_CLI_VAULT_KEY = sealed.key;
95
+ } catch {
96
+ // No key saved yet, or it expired: ente will fall back to the keychain,
97
+ // which is exactly what a `session` policy would have done.
98
+ }
99
+ return env;
100
+ }
101
+
77
102
  async function runEnte(args: string[], signal?: AbortSignal): Promise<Run> {
78
103
  const bin = resolveEnte();
79
104
  if (!bin) throw new EnteError(ENTE_MISSING, 127);
80
105
  if (signal?.aborted) throw new EnteError("Cancelled.", 4);
106
+ const env = await enteEnv(signal);
81
107
  return new Promise<Run>((resolve, reject) => {
82
- const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
108
+ const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"], env });
83
109
  let stdout = "";
84
110
  let stderr = "";
85
111
  const onAbort = () => child.kill("SIGKILL");
@@ -636,7 +636,8 @@ const HELP = [
636
636
  "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
637
637
  "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
638
638
  "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
639
- "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.unlock、bitwarden.import …)",
639
+ "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)",
640
+ "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)",
640
641
  "/vault status 状态与授权剩余时间",
641
642
  "/vault list 本地条目元数据",
642
643
  "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
@@ -711,6 +712,9 @@ function settingsText(s: Settings): string {
711
712
  `bitwarden.hours: ${s.bitwarden.hours}`,
712
713
  `bitwarden.import: ${s.bitwarden.import} (ask | always | never)`,
713
714
  `bitwarden 已落盘的会话: ${persisted}`,
715
+ `ente.unlock: ${s.ente.unlock} (never | time | session)`,
716
+ `ente.hours: ${s.ente.hours}`,
717
+ `ente 已落盘的密钥: ${s.ente.persisted ? "有" : "无"}`,
714
718
  ].join("\n");
715
719
  }
716
720
 
@@ -782,6 +786,24 @@ function commandHandler(scope: Scope, bw: BwState) {
782
786
  }
783
787
  return;
784
788
  }
789
+ case "ente-key": {
790
+ // Ente's unattended key: generated by `ente vault key generate`.
791
+ // Saved sealed, so `ente.unlock = never | time` can use it.
792
+ const key = await promptSecret(dialogs(ctx), "ai-vault · Ente 密钥", "ente vault key generate 输出的密钥");
793
+ if (!key) {
794
+ note(ctx, "已取消", "warning");
795
+ return;
796
+ }
797
+ try {
798
+ const args = ["ente-session", "put"];
799
+ await cli.run(args, { stdin: key });
800
+ forgetSettings();
801
+ note(ctx, "已保存(封存)。现在可以设置 /vault settings ente.unlock never");
802
+ } catch (error) {
803
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
804
+ }
805
+ return;
806
+ }
785
807
  case "settings": {
786
808
  const [key, ...valueParts] = rest;
787
809
  const value = valueParts.join(" ").trim();
@@ -19,11 +19,14 @@ export interface Settings {
19
19
  persisted: boolean;
20
20
  expiresAt: number | null;
21
21
  };
22
+ /** Ente's ENTE_CLI_VAULT_KEY: session leaves it to the OS keychain. */
23
+ ente: { unlock: UnlockModeName; hours: number; persisted: boolean; expiresAt: number | null };
22
24
  }
23
25
 
24
26
  export const DEFAULT_SETTINGS: Settings = {
25
27
  vault: { unlock: "session", hours: 8, auto: false },
26
28
  bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
29
+ ente: { unlock: "session", hours: 8, persisted: false, expiresAt: null },
27
30
  };
28
31
 
29
32
  const cli = new VaultCli();
package/test/cli.sh CHANGED
@@ -155,6 +155,17 @@ check "without the wrap key the session does not open" 1 "$BIN" bw-session get
155
155
  mv "$TMP/wrap.bak" "$AI_VAULT_DIR/.wrap"
156
156
  "$BIN" settings bitwarden.unlock session --json >/dev/null
157
157
 
158
+ echo "== ente sealed key (M4 pattern) =="
159
+ check "ente.unlock is readable" 0 "$BIN" settings ente.unlock --json
160
+ check "ente-session put refused in session mode" 1 bash -c "printf 'K' | '$BIN' ente-session put"
161
+ check "switch ente.unlock to never" 0 "$BIN" settings ente.unlock never --json
162
+ check "store the Ente vault key" 0 bash -c "printf 'ENTE_KEY_PLAINTEXT' | '$BIN' ente-session put --json"
163
+ grep -q 'ENTE_KEY_PLAINTEXT' "$AI_VAULT_DIR/ente.session.json" && bad "the ente key is plaintext on disk" || ok "the ente key is sealed at rest"
164
+ [[ "$(stat -c %a "$AI_VAULT_DIR/ente.session.json")" == "600" ]] && ok "ente.session.json is 0600" || bad "ente.session.json is not 0600"
165
+ "$BIN" ente-session get --json | grep -q 'ENTE_KEY_PLAINTEXT' && ok "ente-session get unseals it" || bad "ente-session get cannot unseal"
166
+ "$BIN" settings ente.unlock session --json >/dev/null
167
+ check "switching back to session clears the ente key" 5 "$BIN" ente-session get
168
+
158
169
  echo "== rekey (L2) =="
159
170
  OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
160
171
  check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
@@ -170,7 +181,7 @@ python3 - "$TMP/audit" <<'PY' && ok "the audit log records events without values
170
181
  import json,sys
171
182
  entries = json.load(open(sys.argv[1]))["entries"]
172
183
  events = {e["event"] for e in entries}
173
- for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock", "rekey", "bw_session"):
184
+ for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock", "rekey", "sealed"):
174
185
  assert want in events, (want, events)
175
186
  assert not any("p1ssw0rd" in json.dumps(e) or "exp-pass" in json.dumps(e) for e in entries)
176
187
  PY
@@ -2,8 +2,11 @@ import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { readFileSync, writeFileSync, rmSync } from "node:fs";
4
4
  import { join } from "node:path";
5
+ import { spawnSync } from "node:child_process";
5
6
  import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, textOf, useMocks } from "./helpers.mjs";
6
7
 
8
+ const { forgetSettings } = await import("../packages/pi-ai-vault/src/settings.ts");
9
+
7
10
  const dir = useMocks();
8
11
  const { default: aiVault } = await import("../packages/pi-ai-vault/src/index.ts");
9
12
  cleanUpOnExit(dir);
@@ -84,3 +87,51 @@ test("a failed sync falls back to the offline cache", async () => {
84
87
  assert.equal(result.isError, undefined, textOf(result));
85
88
  assert.equal(JSON.parse(textOf(result)).length, 3);
86
89
  });
90
+
91
+ const enteEnv = () => {
92
+ try {
93
+ return readFileSync(join(dir, "ente.env"), "utf8").trim();
94
+ } catch {
95
+ return "";
96
+ }
97
+ };
98
+
99
+ test("session mode passes no vault key: the OS keychain stays in charge", async () => {
100
+ const bin = process.env.AI_VAULT_BIN;
101
+ spawnSync(bin, ["settings", "ente.unlock", "session"], { env: process.env });
102
+ forgetSettings();
103
+ const b = bind(aiVault, true);
104
+ await b.tool("ente_list", {}, makeCtx().ctx);
105
+ assert.match(enteEnv(), /^key=$/m);
106
+ });
107
+
108
+ test("ente.unlock=never feeds the sealed key to the ente child", async () => {
109
+ const bin = process.env.AI_VAULT_BIN;
110
+ const set = spawnSync(bin, ["settings", "ente.unlock", "never"], { env: process.env, encoding: "utf8" });
111
+ assert.equal(set.status, 0, set.stderr);
112
+ const put = spawnSync(bin, ["ente-session", "put"], { input: "MY_SECRET_VAULT_KEY", env: process.env, encoding: "utf8" });
113
+ assert.equal(put.status, 0, put.stderr);
114
+ forgetSettings();
115
+
116
+ const b = bind(aiVault, true);
117
+ const result = await b.tool("ente_list", {}, makeCtx().ctx);
118
+ assert.equal(result.isError, undefined, textOf(result));
119
+ assert.match(enteEnv(), /^key=MY_SECRET_VAULT_KEY$/m);
120
+ });
121
+
122
+ test("an inherited ENTE_CLI_VAULT_KEY is not trusted in session mode", async () => {
123
+ const bin = process.env.AI_VAULT_BIN;
124
+ spawnSync(bin, ["settings", "ente.unlock", "session"], { env: process.env });
125
+ spawnSync(bin, ["ente-session", "clear"], { env: process.env });
126
+ forgetSettings();
127
+ const previous = process.env.ENTE_CLI_VAULT_KEY;
128
+ process.env.ENTE_CLI_VAULT_KEY = "LEAKED_FROM_SHELL";
129
+ try {
130
+ const b = bind(aiVault, true);
131
+ await b.tool("ente_list", {}, makeCtx().ctx);
132
+ assert.match(enteEnv(), /^key=$/m, "the shell-exported key must not reach ente");
133
+ } finally {
134
+ if (previous === undefined) delete process.env.ENTE_CLI_VAULT_KEY;
135
+ else process.env.ENTE_CLI_VAULT_KEY = previous;
136
+ }
137
+ });
package/tests/helpers.mjs CHANGED
@@ -40,6 +40,9 @@ export function useMocks() {
40
40
  process.env.ENTE_MOCK_DIR = dir;
41
41
  process.env.AI_VAULT_DIR = join(dir, "vault");
42
42
  process.env.AI_VAULT_BIN = cliBinary();
43
+ // The extension resolves the CLI from PATH; the tests pass one explicitly.
44
+ // Put the same build first so both halves run the same version.
45
+ process.env.PATH = `${dirname(process.env.AI_VAULT_BIN)}:${process.env.PATH}`;
43
46
  return dir;
44
47
  }
45
48
 
@@ -9,7 +9,14 @@
9
9
  # the list path never asked for a code.
10
10
  DIR="${ENTE_MOCK_DIR:-/tmp/ente-mock}"
11
11
  mkdir -p "$DIR"
12
+ # Record whether a vault key reached us and which, so tests can tell a
13
+ # keychain-backed run (nothing) from a sealed-key run (a value).
12
14
  printf '%s\n' "$*" >>"$DIR/ente.log"
15
+ if [[ -n "${ENTE_CLI_VAULT_KEY:-}" ]]; then
16
+ printf 'key=%s\n' "$ENTE_CLI_VAULT_KEY" >>"$DIR/ente.env"
17
+ else
18
+ printf 'key=\n' >>"$DIR/ente.env"
19
+ fi
13
20
  if [[ -f "$DIR/unauthenticated" ]]; then
14
21
  echo "no account logged in; run ente account login --app auth" >&2
15
22
  exit 3