@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.
@@ -78,6 +78,15 @@ pub struct UnlockPolicy {
78
78
  /// `Time` mode only: hours between password prompts.
79
79
  #[serde(default = "default_hours")]
80
80
  pub hours: i64,
81
+ /// Whether each read of an entry opens a confirm window while the session
82
+ /// is unlocked. On by default. Off means "the master password I just typed
83
+ /// is enough" — reads are still audited, entry by entry.
84
+ #[serde(default = "default_confirm")]
85
+ pub confirm: bool,
86
+ }
87
+
88
+ fn default_confirm() -> bool {
89
+ true
81
90
  }
82
91
 
83
92
  fn default_hours() -> i64 {
@@ -86,7 +95,7 @@ fn default_hours() -> i64 {
86
95
 
87
96
  impl Default for UnlockPolicy {
88
97
  fn default() -> Self {
89
- UnlockPolicy { mode: UnlockMode::Session, hours: default_hours() }
98
+ UnlockPolicy { mode: UnlockMode::Session, hours: default_hours(), confirm: default_confirm() }
90
99
  }
91
100
  }
92
101
 
@@ -142,18 +151,37 @@ pub struct Config {
142
151
  pub ente: StorePolicy,
143
152
  }
144
153
 
145
- /// A missing or unreadable config means the defaults. A broken file must not
146
- /// lock anyone out of their vault.
147
- pub fn load(paths: &Paths) -> Config {
148
- match fs::read_to_string(paths.config()) {
149
- Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
150
- Err(_) => Config::default(),
154
+ /// The settings are inside the store's ciphertext (see `crypto::Payload`), so
155
+ /// they can only be read or changed with the store's key: a password, or a
156
+ /// session that was opened with one. There is no file to edit.
157
+ //
158
+ // Callers hold either a `Session` (its key opens the store) or a freshly
159
+ // derived key. Both go through `read_with` / `write_with`.
160
+ pub fn write_with(
161
+ store: &crate::crypto::StoreFile,
162
+ key: &[u8; 32],
163
+ config: &Config,
164
+ ) -> Result<crate::crypto::StoreFile, String> {
165
+ let payload = crypto::open_with_key(store, key).map_err(|e| e.to_string())?;
166
+ let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| "vault salt is corrupt".to_string())?;
167
+ crypto::seal(&salt, store.kdf(), key, &payload.items, config)
168
+ }
169
+
170
+ /// A legacy plaintext config.json from before the settings moved inside the
171
+ /// store. Returned once so the next unlock can carry it in; then the file
172
+ /// is removed. Only the *defaults-safe* keys migrate; the two that lower
173
+ /// protection (`vault.unlock = never`, `vault.confirm = false`) do not, so
174
+ /// an edit made while the file was still plain text grants nothing.
175
+ pub fn take_legacy(paths: &Paths) -> Option<Config> {
176
+ let text = fs::read_to_string(paths.config()).ok()?;
177
+ let _ = fs::remove_file(paths.config());
178
+ let Ok(parsed) = serde_json::from_str::<Config>(&text) else { return None };
179
+ let mut config = parsed;
180
+ if config.unlock.mode == UnlockMode::Never {
181
+ config.unlock.mode = UnlockMode::Session;
151
182
  }
152
- }
153
-
154
- pub fn save(paths: &Paths, config: &Config) -> Result<(), String> {
155
- let bytes = serde_json::to_vec_pretty(config).map_err(|e| format!("cannot serialize config: {e}"))?;
156
- crypto::write_atomic(&paths.config(), &bytes)
183
+ config.unlock.confirm = true;
184
+ Some(config)
157
185
  }
158
186
 
159
187
  #[cfg(test)]
@@ -183,6 +211,7 @@ mod tests {
183
211
  // A config written by the previous version had only `unlock`.
184
212
  let parsed: Config = serde_json::from_str(r#"{"unlock":{"mode":"time","hours":4}}"#).unwrap();
185
213
  assert_eq!(parsed.unlock.mode, UnlockMode::Time);
214
+ assert_eq!(parsed.unlock.confirm, true, "a config from before the switch keeps confirming");
186
215
  assert_eq!(parsed.bitwarden.import, ImportPolicy::Ask);
187
216
  assert_eq!(parsed.bitwarden.store.hours, 8);
188
217
  }
@@ -115,8 +115,20 @@ pub fn store_id(store: &StoreFile) -> String {
115
115
  digest.iter().take(12).map(|b| format!("{b:02x}")).collect()
116
116
  }
117
117
 
118
- pub fn seal(salt: &[u8], kdf: Kdf, key: &[u8; 32], items: &[Item]) -> Result<StoreFile, String> {
119
- let plaintext = serde_json::to_vec(items).map_err(|e| format!("cannot serialize vault: {e}"))?;
118
+ /// What the ciphertext holds: the entries and the settings together, so the
119
+ /// settings are protected by the same key as the passwords and cannot be
120
+ /// edited on disk. `v: 1` files (before settings moved in) hold a bare array
121
+ /// of items and are read as "all defaults".
122
+ #[derive(Debug, Clone, Serialize, Deserialize)]
123
+ pub struct Payload {
124
+ pub items: Vec<Item>,
125
+ #[serde(default)]
126
+ pub config: crate::config::Config,
127
+ }
128
+
129
+ pub fn seal(salt: &[u8], kdf: Kdf, key: &[u8; 32], items: &[Item], config: &crate::config::Config) -> Result<StoreFile, String> {
130
+ let plaintext = serde_json::to_vec(&Payload { items: items.to_vec(), config: *config })
131
+ .map_err(|e| format!("cannot serialize vault: {e}"))?;
120
132
  let iv = random_bytes::<12>();
121
133
  let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| format!("bad key: {e}"))?;
122
134
  let body = cipher
@@ -133,7 +145,7 @@ pub fn seal(salt: &[u8], kdf: Kdf, key: &[u8; 32], items: &[Item]) -> Result<Sto
133
145
  })
134
146
  }
135
147
 
136
- pub fn open_with_key(store: &StoreFile, key: &[u8; 32]) -> Result<Vec<Item>, OpenError> {
148
+ pub fn open_with_key(store: &StoreFile, key: &[u8; 32]) -> Result<Payload, OpenError> {
137
149
  if store.v != 1 {
138
150
  return Err(OpenError::Broken("unsupported vault format".into()));
139
151
  }
@@ -146,16 +158,21 @@ pub fn open_with_key(store: &StoreFile, key: &[u8; 32]) -> Result<Vec<Item>, Ope
146
158
  let (iv, body) = blob.split_at(12);
147
159
  let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|_| OpenError::Broken("bad key".into()))?;
148
160
  let plaintext = cipher
149
- .decrypt(Nonce::from_slice(iv), body)
150
- .map_err(|_| OpenError::WrongPassword)?;
151
- serde_json::from_slice(&plaintext).map_err(|_| OpenError::Broken("vault contents are not a list of entries".into()))
161
+ .decrypt(Nonce::from_slice(iv), body).map_err(|_| OpenError::WrongPassword)?;
162
+ // A bare array is a v1 store written before settings lived inside; the
163
+ // defaults apply to it. A wrong password cannot reach here (the tag
164
+ // fails first), so a parse error really is a format problem.
165
+ if let Ok(items) = serde_json::from_slice::<Vec<Item>>(&plaintext) {
166
+ return Ok(Payload { items, config: crate::config::Config::default() });
167
+ }
168
+ serde_json::from_slice(&plaintext).map_err(|_| OpenError::Broken("vault contents are not a store this version understands".into()))
152
169
  }
153
170
 
154
- pub fn open_with_passphrase(store: &StoreFile, passphrase: &str) -> Result<(Vec<Item>, Key), OpenError> {
171
+ pub fn open_with_passphrase(store: &StoreFile, passphrase: &str) -> Result<(Payload, Key), OpenError> {
155
172
  let salt = hex_to_bytes(&store.salt).ok_or_else(|| OpenError::Broken("vault salt is not hex".into()))?;
156
173
  let key = derive_key(passphrase, &salt, store.kdf())?;
157
- let items = open_with_key(store, &key)?;
158
- Ok((items, key))
174
+ let payload = open_with_key(store, &key)?;
175
+ Ok((payload, key))
159
176
  }
160
177
 
161
178
  pub fn hex_to_bytes(text: &str) -> Option<Vec<u8>> {
@@ -238,12 +255,12 @@ mod tests {
238
255
  let salt = random_bytes::<16>();
239
256
  let kdf = fast();
240
257
  let key = derive_key("correct horse", &salt, kdf).unwrap();
241
- let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
258
+ let sealed = seal(&salt, kdf, &key, &sample(), &Default::default()).unwrap();
242
259
  let opened = open_with_key(&sealed, &key).unwrap();
243
- assert_eq!(opened.len(), 1);
244
- assert_eq!(opened[0].password, "hunter2");
260
+ assert_eq!(opened.items.len(), 1);
261
+ assert_eq!(opened.items[0].password, "hunter2");
245
262
  let (again, _) = open_with_passphrase(&sealed, "correct horse").unwrap();
246
- assert_eq!(again[0].username.as_deref(), Some("octo"));
263
+ assert_eq!(again.items[0].username.as_deref(), Some("octo"));
247
264
  }
248
265
 
249
266
  #[test]
@@ -251,7 +268,7 @@ mod tests {
251
268
  let salt = random_bytes::<16>();
252
269
  let kdf = fast();
253
270
  let key = derive_key("right", &salt, kdf).unwrap();
254
- let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
271
+ let sealed = seal(&salt, kdf, &key, &sample(), &Default::default()).unwrap();
255
272
  assert!(matches!(open_with_passphrase(&sealed, "wrong"), Err(OpenError::WrongPassword)));
256
273
  }
257
274
 
@@ -259,11 +276,45 @@ mod tests {
259
276
  fn each_seal_uses_a_fresh_iv() {
260
277
  let salt = random_bytes::<16>();
261
278
  let key = derive_key("pw", &salt, fast()).unwrap();
262
- let a = seal(&salt, fast(), &key, &sample()).unwrap();
263
- let b = seal(&salt, fast(), &key, &sample()).unwrap();
279
+ let a = seal(&salt, fast(), &key, &sample(), &Default::default()).unwrap();
280
+ let b = seal(&salt, fast(), &key, &sample(), &Default::default()).unwrap();
264
281
  assert_ne!(a.ct, b.ct);
265
282
  }
266
283
 
284
+ #[test]
285
+ fn settings_live_inside_the_ciphertext() {
286
+ let salt = random_bytes::<16>();
287
+ let kdf = fast();
288
+ let key = derive_key("pw", &salt, kdf).unwrap();
289
+ let mut config = crate::config::Config::default();
290
+ config.unlock.confirm = false;
291
+ let sealed = seal(&salt, kdf, &key, &sample(), &config).unwrap();
292
+ let text = serde_json::to_string(&sealed).unwrap();
293
+ assert!(!text.contains("confirm"), "the settings must not be readable on disk");
294
+ let opened = open_with_key(&sealed, &key).unwrap();
295
+ assert!(!opened.config.unlock.confirm);
296
+ }
297
+
298
+ #[test]
299
+ fn a_v1_bare_array_store_still_opens() {
300
+ use chacha20poly1305::aead::{Aead, KeyInit};
301
+ use chacha20poly1305::{ChaCha20Poly1305, Nonce};
302
+ use base64::Engine as _;
303
+ let salt = random_bytes::<16>();
304
+ let kdf = fast();
305
+ let key = derive_key("pw", &salt, kdf).unwrap();
306
+ let cipher = ChaCha20Poly1305::new_from_slice(key.as_ref()).unwrap();
307
+ let iv = random_bytes::<12>();
308
+ let plain = serde_json::to_vec(&sample()).unwrap();
309
+ let body = cipher.encrypt(Nonce::from_slice(&iv), plain.as_slice()).unwrap();
310
+ let mut blob = iv.to_vec();
311
+ blob.extend_from_slice(&body);
312
+ let v1 = StoreFile { v: 1, salt: salt.iter().map(|b| format!("{b:02x}")).collect(), kdf: Some(kdf), ct: base64::engine::general_purpose::STANDARD.encode(blob) };
313
+ let (payload, _) = open_with_passphrase(&v1, "pw").unwrap();
314
+ assert_eq!(payload.items[0].name, "GitHub");
315
+ assert!(payload.config.unlock.confirm, "a store from before the switch keeps the safe default");
316
+ }
317
+
267
318
  #[test]
268
319
  fn refuses_a_downgraded_kdf() {
269
320
  let weak = Kdf { n: 1 << 12, r: 8, p: 1 };
@@ -276,9 +327,9 @@ mod tests {
276
327
  // Written by the TS release, with the default KDF.
277
328
  let salt = "00112233445566778899aabbccddeeff";
278
329
  let key = derive_key("pw", &hex_to_bytes(salt).unwrap(), fast()).unwrap();
279
- let sealed = seal(&hex_to_bytes(salt).unwrap(), fast(), &key, &sample()).unwrap();
330
+ let sealed = seal(&hex_to_bytes(salt).unwrap(), fast(), &key, &sample(), &Default::default()).unwrap();
280
331
  let json = serde_json::json!({ "v": 1, "salt": salt, "kdf": { "N": 32768, "r": 8, "p": 1 }, "ct": sealed.ct });
281
332
  let store: StoreFile = serde_json::from_value(json).unwrap();
282
- assert_eq!(open_with_passphrase(&store, "pw").unwrap().0[0].name, "GitHub");
333
+ assert_eq!(open_with_passphrase(&store, "pw").unwrap().0.items[0].name, "GitHub");
283
334
  }
284
335
  }
@@ -33,12 +33,6 @@ impl Kind {
33
33
  }
34
34
  }
35
35
 
36
- fn policy(self, config: &config::Config) -> config::StorePolicy {
37
- match self {
38
- Kind::Bitwarden => config.bitwarden.store,
39
- Kind::Ente => config.ente,
40
- }
41
- }
42
36
  }
43
37
 
44
38
  #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -124,9 +118,7 @@ impl Stored {
124
118
 
125
119
  /// Store a key, honouring the current `bitwarden.unlock` policy. `session`
126
120
  /// means "do not persist": the caller keeps it in memory instead.
127
- pub fn save(paths: &Paths, kind: Kind, secret: &str) -> Result<Option<i64>, String> {
128
- let config = config::load(paths);
129
- let policy = kind.policy(&config);
121
+ pub fn save(paths: &Paths, kind: Kind, secret: &str, policy: config::StorePolicy) -> Result<Option<i64>, String> {
130
122
  if policy.unlock == UnlockMode::Session {
131
123
  clear(paths, kind);
132
124
  return Err(format!(
@@ -54,9 +54,42 @@ pub struct Session {
54
54
  /// by definition not protected from this user.
55
55
  #[serde(default, skip_serializing_if = "Option::is_none", rename = "mac")]
56
56
  pub mac: Option<String>,
57
+ /// Which key signed `mac`: "host" (the extension's in-memory secret) or
58
+ /// "wrap" (the store's key, for a human at a terminal). Verification uses
59
+ /// the key actually named here, never whichever one happens to be in the
60
+ /// environment — so a token created one way is not voided by a call made
61
+ /// the other way.
62
+ #[serde(default, skip_serializing_if = "Option::is_none", rename = "signedBy")]
63
+ pub signed_by: Option<String>,
57
64
  }
58
65
 
59
66
 
67
+ /// Who signs a session file: the host process's in-memory secret, or the
68
+ /// store's wrap key when a human runs `ai-vault` by hand.
69
+ pub enum Signer {
70
+ Host(String),
71
+ Wrap(String),
72
+ }
73
+
74
+ impl Signer {
75
+ fn label(&self) -> &'static str {
76
+ match self {
77
+ Signer::Host(_) => "host",
78
+ Signer::Wrap(_) => "wrap",
79
+ }
80
+ }
81
+
82
+ fn hmac(&self, body: &[u8]) -> String {
83
+ use hmac::{Hmac, Mac};
84
+ let key = match self {
85
+ Signer::Host(k) | Signer::Wrap(k) => k.as_str(),
86
+ };
87
+ let mut hasher = <Hmac<sha2::Sha256> as Mac>::new_from_slice(key.as_bytes()).expect("HMAC takes any key length");
88
+ hasher.update(body);
89
+ hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()
90
+ }
91
+ }
92
+
60
93
  fn mac_body(session: &Session) -> Vec<u8> {
61
94
  // Same struct, `mac` blanked, canonical key order: serde_json::Value sorts
62
95
  // object keys, so the encoding is stable across runs.
@@ -83,35 +116,48 @@ impl Session {
83
116
  key: B64.encode(key),
84
117
  grants: BTreeMap::new(),
85
118
  mac: None,
119
+ signed_by: None,
86
120
  }
87
121
  }
88
122
 
89
- /// (Re)sign this session with the host's secret. Called before every save.
90
- pub fn sign(&mut self, host_secret: Option<&str>) {
91
- self.mac = host_secret.map(|secret| {
92
- use hmac::{Hmac, Mac};
93
- let mut hasher = <Hmac<sha2::Sha256> as Mac>::new_from_slice(secret.as_bytes())
94
- .expect("HMAC takes any key length");
95
- hasher.update(&mac_body(self));
96
- hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()
97
- });
123
+ /// (Re)sign this session and record who signed it. Called before every save.
124
+ pub fn sign(&mut self, signer: &Signer) {
125
+ self.signed_by = Some(signer.label().to_string());
126
+ let body = mac_body(self);
127
+ self.mac = Some(signer.hmac(&body));
98
128
  }
99
129
 
100
- /// True when the file was written by a process holding `host_secret`.
101
- /// A session with no mac at all is only valid as the `never`-mode session.
102
- pub fn verifies(&self, host_secret: Option<&str>) -> bool {
103
- let (Some(secret), Some(mac)) = (host_secret, self.mac.as_deref()) else {
104
- // The only legitimate unsigned session is the machine-wide one.
105
- return self.mac.is_none() && host_secret.is_none();
130
+ /// True when the file was written by whoever it says signed it, checked
131
+ /// with *that* key — never whichever one happens to be in the environment.
132
+ pub fn verifies(&self, host_secret: Option<&str>, wrap_key: Option<&str>) -> bool {
133
+ let Some(mac) = self.mac.as_deref() else {
134
+ // The only legitimate unsigned session is the machine-wide one,
135
+ // which is protected by the directory instead.
136
+ return host_secret.is_none() && wrap_key.is_none();
137
+ };
138
+ let key: &str = match self.signed_by.as_deref() {
139
+ Some("host") => match host_secret {
140
+ Some(k) => k,
141
+ None => return false,
142
+ },
143
+ Some("wrap") => match wrap_key {
144
+ Some(k) => k,
145
+ None => return false,
146
+ },
147
+ // A file from before `signedBy`: accept whichever key fits.
148
+ _ => match host_secret.or(wrap_key) {
149
+ Some(k) => k,
150
+ None => return false,
151
+ },
106
152
  };
107
153
  use hmac::{Hmac, Mac};
108
- let Ok(mut hasher) = <Hmac<sha2::Sha256> as Mac>::new_from_slice(secret.as_bytes()) else {
154
+ let Ok(mut hasher) = <Hmac<sha2::Sha256> as Mac>::new_from_slice(key.as_bytes()) else {
109
155
  return false;
110
156
  };
111
157
  hasher.update(&mac_body(self));
112
158
  let expected: String = hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
113
- // Constant-time compare is not required for a 256-bit tag, but cheap.
114
- expected.len() == mac.len() && expected.bytes().zip(mac.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0
159
+ expected.len() == mac.len()
160
+ && expected.bytes().zip(mac.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0
115
161
  }
116
162
 
117
163
  pub fn key(&self) -> Option<Zeroizing<[u8; 32]>> {
@@ -152,9 +198,9 @@ impl Session {
152
198
  .filter(|until| *until > now)
153
199
  }
154
200
 
155
- pub fn save(&self, paths: &Paths, host_secret: Option<&str>) -> Result<(), String> {
201
+ pub fn save(&self, paths: &Paths, signer: &Signer) -> Result<(), String> {
156
202
  let mut signed = self.clone();
157
- signed.sign(host_secret);
203
+ signed.sign(signer);
158
204
  let dir = paths.sessions();
159
205
  fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
160
206
  crate::perms::restrict_dir(&dir);
@@ -165,7 +211,7 @@ impl Session {
165
211
 
166
212
  /// Load a token for the given store. Missing, expired, or stale tokens are
167
213
  /// removed and reported as locked so the caller unlocks again.
168
- pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>) -> Result<Session, String> {
214
+ pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>, wrap_key: Option<&str>) -> Result<Session, String> {
169
215
  let path = paths.session_file(token);
170
216
  let text = match fs::read_to_string(&path) {
171
217
  Ok(text) => text,
@@ -183,7 +229,18 @@ pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>) -> Result<Ses
183
229
  }
184
230
  // Edited on disk (a grant minted, a requester renamed): treat as a break-in
185
231
  // attempt, say so, and drop it.
186
- if !session.verifies(host_secret) {
232
+ // Only a file this caller holds a key for is judged; one signed under a
233
+ // key the caller does not have is simply not theirs to use (and is left
234
+ // alone for whoever does hold that key).
235
+ let has_key_for_it = match session.signed_by.as_deref() {
236
+ Some("host") => host_secret.is_some(),
237
+ Some("wrap") => wrap_key.is_some(),
238
+ _ => host_secret.is_some() || wrap_key.is_some(),
239
+ };
240
+ if !has_key_for_it {
241
+ return Err("this session belongs to another caller — unlock again".into());
242
+ }
243
+ if !session.verifies(host_secret, wrap_key) {
187
244
  let _ = fs::remove_file(&path);
188
245
  return Err("session file was modified outside ai-vault — unlock again".into());
189
246
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaolikt/ai-vault",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable, Linux/macOS/Windows) plus the pi-ai-vault extension for pi and omp.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,9 +33,9 @@
33
33
  "access": "public"
34
34
  },
35
35
  "optionalDependencies": {
36
- "@xiaolikt/ai-vault-linux-x64": "0.11.0",
37
- "@xiaolikt/ai-vault-linux-arm64": "0.11.0",
38
- "@xiaolikt/ai-vault-win32-x64": "0.11.0"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.12.0",
37
+ "@xiaolikt/ai-vault-linux-arm64": "0.12.0",
38
+ "@xiaolikt/ai-vault-win32-x64": "0.12.0"
39
39
  },
40
40
  "files": [
41
41
  "bin",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store, live Bitwarden and Ente Auth. 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.11.0"
28
+ "@xiaolikt/ai-vault": "0.12.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
@@ -56,7 +56,7 @@ import { bitwardenItems, filterItems } from "./import-map.js";
56
56
  import type { Draft } from "./types.js";
57
57
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
58
58
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
59
- import { getSettingsSafe, settingsCli } from "./settings.js";
59
+ import { getSettingsSafe, settingsCli, settingsToken } from "./settings.js";
60
60
  import { tr } from "./i18n.js";
61
61
  import { scrubDeep, scrubText } from "./scrub.js";
62
62
 
@@ -603,7 +603,8 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
603
603
  if (policy.unlock !== "session") {
604
604
  // Keep the key where the CLI can hand it back; the file's expiry comes
605
605
  // from the bitwarden.hours policy.
606
- await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
606
+ const token = settingsToken();
607
+ await settingsCli().run(["bw-session", "put", ...(token ? ["--token", token] : [])], { stdin: key }).catch(() => undefined);
607
608
  }
608
609
  await auditEvent("unlock", "ok", st.sessionLabel);
609
610
  // Refresh in the background: a full sync can take seconds on large vaults.
@@ -23,13 +23,13 @@ import {
23
23
  type BitwardenMeta,
24
24
  type BwState,
25
25
  } from "./bitwarden.js";
26
- import { CliError, VaultCli } from "./cli.js";
26
+ import { CliError } from "./cli.js";
27
27
  import { ITEM_TYPES, isSecretField, parseItemType } from "./import-map.js";
28
28
  import type { Draft, ItemType } from "./types.js";
29
29
  import { registerEnte } from "./ente.js";
30
30
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
31
31
  import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
32
- import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
32
+ import { forgetSettings, getSettingsSafe, setSettingsToken, settingsCli, settingsToken, type Settings } from "./settings.js";
33
33
 
34
34
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
35
35
 
@@ -100,7 +100,7 @@ interface Scope {
100
100
  unlocking?: Promise<boolean>;
101
101
  }
102
102
 
103
- const cli = new VaultCli();
103
+ const cli = settingsCli();
104
104
 
105
105
  const CLI_MISSING =
106
106
  tr("ai-vault CLI not found. Install it once for a machine-wide store: cargo install --path <repo>/crates/ai-vault (or point AI_VAULT_BIN at a compiled binary)", "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)");
@@ -148,6 +148,8 @@ async function lockNow(scope: Scope): Promise<void> {
148
148
  scope.token = undefined;
149
149
  scope.epoch++;
150
150
  scope.items = 0;
151
+ setSettingsToken(undefined);
152
+ forgetSettings();
151
153
  if (!token || !cli.available) return;
152
154
  try {
153
155
  await cli.run(["lock", "--token", token]);
@@ -174,6 +176,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
174
176
  scope.items = status.items;
175
177
  scope.mode = status.mode;
176
178
  scope.auto = false;
179
+ setSettingsToken(scope.token);
177
180
  return true;
178
181
  } catch (error) {
179
182
  if (!(error instanceof CliError) || !error.auth) {
@@ -194,6 +197,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
194
197
  scope.items = status.items;
195
198
  scope.mode = status.mode;
196
199
  scope.auto = status.auto;
200
+ setSettingsToken(undefined);
197
201
  return true;
198
202
  } catch (error) {
199
203
  if (error instanceof CliError && /not initialized/i.test(error.message)) {
@@ -237,6 +241,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
237
241
  // per-binding token would bring back a confirm window on every read.
238
242
  scope.token = result.mode === "never" ? undefined : result.token;
239
243
  scope.items = result.items;
244
+ setSettingsToken(scope.token);
240
245
  return true;
241
246
  } catch (error) {
242
247
  if (error instanceof CliError && error.auth) {
@@ -693,6 +698,7 @@ const HELP = [
693
698
  tr("/vault init create the machine-wide encrypted store (a dialog sets the master password)", "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)"),
694
699
  tr("/vault unlock | lock unlock / lock (clears this session's grants)", "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)"),
695
700
  tr("/vault mode [never|time|session] show/switch the unlock policy (switching needs the master password)", "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)"),
701
+ tr("/vault confirm [off|on] a window per read while unlocked (off asks the master password)", "/vault confirm [off|on] 解锁后每次读取是否弹确认窗(关要主密码)"),
696
702
  tr("/vault settings [key value] show/change settings (vault.unlock, bitwarden.*, ente.* …)", "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)"),
697
703
  tr("/vault ente-key save Ente's ENTE_CLI_VAULT_KEY (no keychain, no login)", "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)"),
698
704
  tr("/vault status state and grants left", "/vault status 状态与授权剩余时间"),
@@ -861,22 +867,61 @@ function commandHandler(scope: Scope, bw: BwState) {
861
867
  }
862
868
  return;
863
869
  }
870
+ case "confirm": {
871
+ // /vault confirm show
872
+ // /vault confirm off|on turn the per-read window off (asks the master password) / on
873
+ const [arg] = rest;
874
+ if (!arg) {
875
+ try {
876
+ const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)]);
877
+ note(ctx, `vault.confirm: ${current.vault.confirm}${current.vault.confirm ? tr(" (a window per read while unlocked)", " (解锁后每次读取弹确认窗)") : tr(" (the unlock is the approval; reads are audited)", " (解锁即授权;读取仍记审计)")}`);
878
+ } catch (error) {
879
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
880
+ }
881
+ return;
882
+ }
883
+ const value = arg.toLowerCase();
884
+ if (!["off", "on", "false", "true"].includes(value)) {
885
+ note(ctx, tr("usage: /vault confirm [off|on]", "用法: /vault confirm [off|on]"), "warning");
886
+ return;
887
+ }
888
+ const turnOff = value === "off" || value === "false";
889
+ try {
890
+ const run = await cli.withPassword(["settings", "vault.confirm", turnOff ? "false" : "true", ...tokenArgs(scope)], () =>
891
+ promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("turn off the per-read confirmation", "关闭每次读取的确认窗")),
892
+ );
893
+ forgetSettings();
894
+ const updated = JSON.parse(run.stdout) as Settings;
895
+ note(
896
+ ctx,
897
+ updated.vault.confirm
898
+ ? tr("vault.confirm is on: every read opens a confirm window.", "vault.confirm 已开:每次读取弹确认窗。")
899
+ : tr(
900
+ "vault.confirm is off: while a session is unlocked, reads return without a window. Each read is still written to the audit log. Turning it back on: /vault confirm on",
901
+ "vault.confirm 已关:会话解锁期间读取不再弹窗。每次读取仍写审计。重新打开:/vault confirm on",
902
+ ),
903
+ );
904
+ } catch (error) {
905
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
906
+ }
907
+ return;
908
+ }
864
909
  case "settings": {
865
910
  const [key, ...valueParts] = rest;
866
911
  const value = valueParts.join(" ").trim();
867
912
  try {
868
913
  if (!key) {
869
- note(ctx, settingsText(await cli.json<Settings>(["settings"])));
914
+ note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)])));
870
915
  return;
871
916
  }
872
917
  if (!value) {
873
- const one = await cli.json<{ key: string; value: string }>(["settings", key]);
918
+ const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)]);
874
919
  note(ctx, `${one.key}: ${one.value}`);
875
920
  return;
876
921
  }
877
922
  // `vault.unlock` opens its own password window (or answers
878
923
  // needs-ui); the other keys do not prompt at all.
879
- const run = await cli.withPassword(["settings", key, value], () =>
924
+ const run = await cli.withPassword(["settings", key, value, ...tokenArgs(scope)], () =>
880
925
  promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
881
926
  );
882
927
  forgetSettings();