@xiaolikt/ai-vault 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Cargo.lock +2 -1
- package/README.md +47 -11
- package/crates/ai-vault/Cargo.toml +2 -1
- package/crates/ai-vault/src/bwsession.rs +86 -5
- package/crates/ai-vault/src/cli.rs +176 -20
- package/crates/ai-vault/src/crypto.rs +34 -8
- package/crates/ai-vault/src/dialog.rs +45 -0
- package/crates/ai-vault/src/paths.rs +8 -1
- package/crates/ai-vault/src/session.rs +82 -13
- package/package.json +2 -2
- package/packages/pi-ai-vault/README.md +4 -0
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/cli.ts +58 -1
- package/packages/pi-ai-vault/src/index.ts +28 -15
- package/packages/pi-ai-vault/src/prompt.ts +13 -0
- package/test/cli.sh +85 -5
- package/tests/prompt.test.mjs +12 -0
- package/tests/vault-cli.test.mjs +33 -0
|
@@ -32,11 +32,22 @@ pub struct Kdf {
|
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
impl Default for Kdf {
|
|
35
|
+
/// 128 MiB of scrypt memory per guess. Files written before this carried
|
|
36
|
+
/// N=2^15 (32 MiB); they open unchanged because the parameters travel in
|
|
37
|
+
/// the file header, and `ai-vault rekey` moves them up.
|
|
35
38
|
fn default() -> Self {
|
|
36
|
-
Kdf { n: 1 <<
|
|
39
|
+
Kdf { n: 1 << 17, r: 8, p: 1 }
|
|
37
40
|
}
|
|
38
41
|
}
|
|
39
42
|
|
|
43
|
+
/// The weakest KDF a file may carry and still be accepted: the old default.
|
|
44
|
+
/// Anything below it is a downgrade, not a legacy file.
|
|
45
|
+
pub const KDF_FLOOR: Kdf = Kdf { n: 1 << 15, r: 8, p: 1 };
|
|
46
|
+
|
|
47
|
+
fn at_or_above_floor(kdf: Kdf) -> bool {
|
|
48
|
+
kdf.n >= KDF_FLOOR.n && kdf.r >= KDF_FLOOR.r && kdf.p >= KDF_FLOOR.p
|
|
49
|
+
}
|
|
50
|
+
|
|
40
51
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
41
52
|
pub struct StoreFile {
|
|
42
53
|
pub v: u32,
|
|
@@ -79,6 +90,9 @@ pub fn random_bytes<const N: usize>() -> [u8; N] {
|
|
|
79
90
|
|
|
80
91
|
/// scrypt(passphrase, salt, N/r/p) -> 32-byte key.
|
|
81
92
|
pub fn derive_key(passphrase: &str, salt: &[u8], kdf: Kdf) -> Result<Key, OpenError> {
|
|
93
|
+
if !at_or_above_floor(kdf) {
|
|
94
|
+
return Err(OpenError::Broken("vault KDF parameters are below the supported minimum".into()));
|
|
95
|
+
}
|
|
82
96
|
let log_n = u8::try_from(kdf.n.trailing_zeros()).map_err(|_| OpenError::Broken("bad KDF parameters".into()))?;
|
|
83
97
|
if kdf.n == 0 || (1u32 << log_n) != kdf.n {
|
|
84
98
|
return Err(OpenError::Broken("bad KDF parameters".into()));
|
|
@@ -221,10 +235,15 @@ mod tests {
|
|
|
221
235
|
items
|
|
222
236
|
}
|
|
223
237
|
|
|
238
|
+
/// The old cost, so the tests below stay fast; correctness is the same.
|
|
239
|
+
fn fast() -> Kdf {
|
|
240
|
+
KDF_FLOOR
|
|
241
|
+
}
|
|
242
|
+
|
|
224
243
|
#[test]
|
|
225
244
|
fn round_trip() {
|
|
226
245
|
let salt = random_bytes::<16>();
|
|
227
|
-
let kdf =
|
|
246
|
+
let kdf = fast();
|
|
228
247
|
let key = derive_key("correct horse", &salt, kdf).unwrap();
|
|
229
248
|
let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
|
|
230
249
|
let opened = open_with_key(&sealed, &key).unwrap();
|
|
@@ -237,7 +256,7 @@ mod tests {
|
|
|
237
256
|
#[test]
|
|
238
257
|
fn wrong_password_is_distinguishable() {
|
|
239
258
|
let salt = random_bytes::<16>();
|
|
240
|
-
let kdf =
|
|
259
|
+
let kdf = fast();
|
|
241
260
|
let key = derive_key("right", &salt, kdf).unwrap();
|
|
242
261
|
let sealed = seal(&salt, kdf, &key, &sample()).unwrap();
|
|
243
262
|
assert!(matches!(open_with_passphrase(&sealed, "wrong"), Err(OpenError::WrongPassword)));
|
|
@@ -246,18 +265,25 @@ mod tests {
|
|
|
246
265
|
#[test]
|
|
247
266
|
fn each_seal_uses_a_fresh_iv() {
|
|
248
267
|
let salt = random_bytes::<16>();
|
|
249
|
-
let key = derive_key("pw", &salt,
|
|
250
|
-
let a = seal(&salt,
|
|
251
|
-
let b = seal(&salt,
|
|
268
|
+
let key = derive_key("pw", &salt, fast()).unwrap();
|
|
269
|
+
let a = seal(&salt, fast(), &key, &sample()).unwrap();
|
|
270
|
+
let b = seal(&salt, fast(), &key, &sample()).unwrap();
|
|
252
271
|
assert_ne!(a.ct, b.ct);
|
|
253
272
|
}
|
|
254
273
|
|
|
274
|
+
#[test]
|
|
275
|
+
fn refuses_a_downgraded_kdf() {
|
|
276
|
+
let weak = Kdf { n: 1 << 12, r: 8, p: 1 };
|
|
277
|
+
assert!(matches!(derive_key("pw", &random_bytes::<16>(), weak), Err(OpenError::Broken(_))));
|
|
278
|
+
assert_eq!(Kdf::default().n, 1 << 17);
|
|
279
|
+
}
|
|
280
|
+
|
|
255
281
|
#[test]
|
|
256
282
|
fn parses_the_typescript_format() {
|
|
257
283
|
// Written by the TS release, with the default KDF.
|
|
258
284
|
let salt = "00112233445566778899aabbccddeeff";
|
|
259
|
-
let key = derive_key("pw", &hex_to_bytes(salt).unwrap(),
|
|
260
|
-
let sealed = seal(&hex_to_bytes(salt).unwrap(),
|
|
285
|
+
let key = derive_key("pw", &hex_to_bytes(salt).unwrap(), fast()).unwrap();
|
|
286
|
+
let sealed = seal(&hex_to_bytes(salt).unwrap(), fast(), &key, &sample()).unwrap();
|
|
261
287
|
let json = serde_json::json!({ "v": 1, "salt": salt, "kdf": { "N": 32768, "r": 8, "p": 1 }, "ct": sealed.ct });
|
|
262
288
|
let store: StoreFile = serde_json::from_value(json).unwrap();
|
|
263
289
|
assert_eq!(open_with_passphrase(&store, "pw").unwrap().0[0].name, "GitHub");
|
|
@@ -130,6 +130,37 @@ fn is_gtk_diagnostic(line: &str) -> bool {
|
|
|
130
130
|
rest.starts_with("Gtk-") || rest.starts_with("Gdk-") || rest.starts_with("GLib-")
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
+
/// Make a caller-supplied value safe to put in a window: one line, bounded,
|
|
134
|
+
/// no control characters. A name or reason that carries newlines could
|
|
135
|
+
/// otherwise forge a second message inside the confirm dialog.
|
|
136
|
+
pub fn for_dialog(value: &str, max: usize) -> String {
|
|
137
|
+
let flat: String = value
|
|
138
|
+
.chars()
|
|
139
|
+
.map(|c| if c.is_control() || c == '\u{2028}' || c == '\u{2029}' { ' ' } else { c })
|
|
140
|
+
.collect();
|
|
141
|
+
let mut out = String::with_capacity(flat.len());
|
|
142
|
+
let mut last_space = false;
|
|
143
|
+
for c in flat.chars() {
|
|
144
|
+
let is_space = c.is_whitespace();
|
|
145
|
+
if is_space {
|
|
146
|
+
if !last_space && !out.is_empty() {
|
|
147
|
+
out.push(' ');
|
|
148
|
+
}
|
|
149
|
+
} else {
|
|
150
|
+
out.push(c);
|
|
151
|
+
}
|
|
152
|
+
last_space = is_space;
|
|
153
|
+
}
|
|
154
|
+
let trimmed = out.trim();
|
|
155
|
+
if trimmed.chars().count() > max {
|
|
156
|
+
let mut cut: String = trimmed.chars().take(max.saturating_sub(1)).collect();
|
|
157
|
+
cut.push('…');
|
|
158
|
+
cut
|
|
159
|
+
} else {
|
|
160
|
+
trimmed.to_string()
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
133
164
|
/// Secret entry. Empty and cancel are both "no value".
|
|
134
165
|
pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
|
|
135
166
|
if !has_display() {
|
|
@@ -202,6 +233,20 @@ pub fn confirm(title: &str, message: &str) -> Answer<bool> {
|
|
|
202
233
|
mod tests {
|
|
203
234
|
use super::*;
|
|
204
235
|
|
|
236
|
+
#[test]
|
|
237
|
+
fn dialog_text_cannot_forge_a_second_line() {
|
|
238
|
+
let forged = "github\n\n条目: nothing\n请求方: 主会话\n(已授权)";
|
|
239
|
+
let clean = for_dialog(forged, 80);
|
|
240
|
+
assert!(!clean.contains('\n'));
|
|
241
|
+
assert!(clean.starts_with("github 条目: nothing"));
|
|
242
|
+
assert_eq!(clean.chars().filter(|c| *c == '…').count(), 0);
|
|
243
|
+
assert_eq!(for_dialog(" a b ", 80), "a b");
|
|
244
|
+
let long = "x".repeat(100);
|
|
245
|
+
let cut = for_dialog(&long, 10);
|
|
246
|
+
assert_eq!(cut.chars().count(), 10);
|
|
247
|
+
assert!(cut.ends_with('…'));
|
|
248
|
+
}
|
|
249
|
+
|
|
205
250
|
#[test]
|
|
206
251
|
fn gtk_diagnostics_are_not_failures() {
|
|
207
252
|
assert!(is_gtk_diagnostic("(zenity:1234): Gtk-WARNING **: cannot open display"));
|
|
@@ -42,11 +42,18 @@ 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
|
|
45
|
+
/// The `bw` session key kept for `bitwarden.unlock = never | time`,
|
|
46
|
+
/// sealed under `wrap_key`.
|
|
46
47
|
pub fn bw_session(&self) -> PathBuf {
|
|
47
48
|
self.dir.join("bitwarden.session.json")
|
|
48
49
|
}
|
|
49
50
|
|
|
51
|
+
/// Random 256-bit key that seals the Bitwarden session at rest, so that
|
|
52
|
+
/// file alone is not a bearer token. Same exposure as the store itself.
|
|
53
|
+
pub fn wrap_key(&self) -> PathBuf {
|
|
54
|
+
self.dir.join(".wrap")
|
|
55
|
+
}
|
|
56
|
+
|
|
50
57
|
/// Shared advisory lock for read-modify-write of the store file.
|
|
51
58
|
pub fn store_lock(&self) -> PathBuf {
|
|
52
59
|
self.dir.join("store.lock")
|
|
@@ -6,6 +6,13 @@
|
|
|
6
6
|
//! token; the key is read from that file, never from the command line. A token
|
|
7
7
|
//! dies on `lock`, after `idleMs` without use, or when the store file changes
|
|
8
8
|
//! underneath it.
|
|
9
|
+
//!
|
|
10
|
+
//! Two things a same-user process must NOT be able to do by editing these
|
|
11
|
+
//! files: mint a grant, and change who the confirm window says is asking.
|
|
12
|
+
//! Every session file therefore carries an HMAC over its whole body, keyed
|
|
13
|
+
//! with a secret that lives in the host process only (`hostSecret`, handed
|
|
14
|
+
//! back once at unlock time, never written to disk). A file that fails the
|
|
15
|
+
//! check is deleted and reported as locked.
|
|
9
16
|
|
|
10
17
|
use std::collections::BTreeMap;
|
|
11
18
|
use std::fs;
|
|
@@ -43,6 +50,22 @@ pub struct Session {
|
|
|
43
50
|
/// entry name (lowercase) -> grant expiry epoch ms
|
|
44
51
|
#[serde(default)]
|
|
45
52
|
pub grants: BTreeMap<String, i64>,
|
|
53
|
+
/// HMAC-SHA256 over every field above (canonical JSON), keyed with the
|
|
54
|
+
/// host secret. Absent only for the machine-wide `never` session, which is
|
|
55
|
+
/// by definition not protected from this user.
|
|
56
|
+
#[serde(default, skip_serializing_if = "Option::is_none", rename = "mac")]
|
|
57
|
+
pub mac: Option<String>,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
fn mac_body(session: &Session) -> Vec<u8> {
|
|
62
|
+
// Same struct, `mac` blanked, canonical key order: serde_json::Value sorts
|
|
63
|
+
// object keys, so the encoding is stable across runs.
|
|
64
|
+
let mut value = serde_json::to_value(session).expect("session serializes");
|
|
65
|
+
if let Some(record) = value.as_object_mut() {
|
|
66
|
+
record.remove("mac");
|
|
67
|
+
}
|
|
68
|
+
value.to_string().into_bytes()
|
|
46
69
|
}
|
|
47
70
|
|
|
48
71
|
impl Session {
|
|
@@ -60,9 +83,38 @@ impl Session {
|
|
|
60
83
|
kdf: Some(store.kdf()),
|
|
61
84
|
key: B64.encode(key),
|
|
62
85
|
grants: BTreeMap::new(),
|
|
86
|
+
mac: None,
|
|
63
87
|
}
|
|
64
88
|
}
|
|
65
89
|
|
|
90
|
+
/// (Re)sign this session with the host's secret. Called before every save.
|
|
91
|
+
pub fn sign(&mut self, host_secret: Option<&str>) {
|
|
92
|
+
self.mac = host_secret.map(|secret| {
|
|
93
|
+
use hmac::{Hmac, Mac};
|
|
94
|
+
let mut hasher = <Hmac<sha2::Sha256> as Mac>::new_from_slice(secret.as_bytes())
|
|
95
|
+
.expect("HMAC takes any key length");
|
|
96
|
+
hasher.update(&mac_body(self));
|
|
97
|
+
hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// True when the file was written by a process holding `host_secret`.
|
|
102
|
+
/// A session with no mac at all is only valid as the `never`-mode session.
|
|
103
|
+
pub fn verifies(&self, host_secret: Option<&str>) -> bool {
|
|
104
|
+
let (Some(secret), Some(mac)) = (host_secret, self.mac.as_deref()) else {
|
|
105
|
+
// The only legitimate unsigned session is the machine-wide one.
|
|
106
|
+
return self.mac.is_none() && host_secret.is_none();
|
|
107
|
+
};
|
|
108
|
+
use hmac::{Hmac, Mac};
|
|
109
|
+
let Ok(mut hasher) = <Hmac<sha2::Sha256> as Mac>::new_from_slice(secret.as_bytes()) else {
|
|
110
|
+
return false;
|
|
111
|
+
};
|
|
112
|
+
hasher.update(&mac_body(self));
|
|
113
|
+
let expected: String = hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
|
|
114
|
+
// Constant-time compare is not required for a 256-bit tag, but cheap.
|
|
115
|
+
expected.len() == mac.len() && expected.bytes().zip(mac.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0
|
|
116
|
+
}
|
|
117
|
+
|
|
66
118
|
pub fn key(&self) -> Option<Zeroizing<[u8; 32]>> {
|
|
67
119
|
let raw = B64.decode(self.key.as_bytes()).ok()?;
|
|
68
120
|
if raw.len() != 32 {
|
|
@@ -101,18 +153,20 @@ impl Session {
|
|
|
101
153
|
.filter(|until| *until > now)
|
|
102
154
|
}
|
|
103
155
|
|
|
104
|
-
pub fn save(&self, paths: &Paths) -> Result<(), String> {
|
|
156
|
+
pub fn save(&self, paths: &Paths, host_secret: Option<&str>) -> Result<(), String> {
|
|
157
|
+
let mut signed = self.clone();
|
|
158
|
+
signed.sign(host_secret);
|
|
105
159
|
let dir = paths.sessions();
|
|
106
160
|
fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
|
107
161
|
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
|
|
108
|
-
let text = serde_json::to_vec(
|
|
109
|
-
crypto::write_atomic(&paths.session_file(&
|
|
162
|
+
let text = serde_json::to_vec(&signed).map_err(|e| format!("cannot serialize session: {e}"))?;
|
|
163
|
+
crypto::write_atomic(&paths.session_file(&signed.token), &text)
|
|
110
164
|
}
|
|
111
165
|
}
|
|
112
166
|
|
|
113
167
|
/// Load a token for the given store. Missing, expired, or stale tokens are
|
|
114
168
|
/// removed and reported as locked so the caller unlocks again.
|
|
115
|
-
pub fn load(paths: &Paths, token: &str) -> Result<Session, String> {
|
|
169
|
+
pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>) -> Result<Session, String> {
|
|
116
170
|
let path = paths.session_file(token);
|
|
117
171
|
let text = match fs::read_to_string(&path) {
|
|
118
172
|
Ok(text) => text,
|
|
@@ -126,7 +180,13 @@ pub fn load(paths: &Paths, token: &str) -> Result<Session, String> {
|
|
|
126
180
|
let now = now_ms();
|
|
127
181
|
if session.expired(now) {
|
|
128
182
|
let _ = fs::remove_file(&path);
|
|
129
|
-
return Err("
|
|
183
|
+
return Err("this session expired — unlock again".into());
|
|
184
|
+
}
|
|
185
|
+
// Edited on disk (a grant minted, a requester renamed): treat as a break-in
|
|
186
|
+
// attempt, say so, and drop it.
|
|
187
|
+
if !session.verifies(host_secret) {
|
|
188
|
+
let _ = fs::remove_file(&path);
|
|
189
|
+
return Err("session file was modified outside ai-vault — unlock again".into());
|
|
130
190
|
}
|
|
131
191
|
let store = crypto::read_store(&paths.store())?.ok_or_else(|| "vault is not initialized".to_string())?;
|
|
132
192
|
if crypto::store_id(&store) != session.store_id || session.key().is_none() {
|
|
@@ -154,9 +214,14 @@ pub fn delete_all(paths: &Paths) -> usize {
|
|
|
154
214
|
removed
|
|
155
215
|
}
|
|
156
216
|
|
|
157
|
-
/// Remove
|
|
158
|
-
///
|
|
217
|
+
/// Remove token files **of this store** that can no longer open anything:
|
|
218
|
+
/// expired, corrupt, or unsigned. Files naming another store are left alone:
|
|
219
|
+
/// several stores may share the sessions directory (two agents, two `--dir`s),
|
|
220
|
+
/// and one store's housekeeping must not lock the other's agents out.
|
|
159
221
|
pub fn sweep(paths: &Paths) -> usize {
|
|
222
|
+
let Some(current) = crypto::read_store(&paths.store()).ok().flatten().map(|store| crypto::store_id(&store)) else {
|
|
223
|
+
return 0;
|
|
224
|
+
};
|
|
160
225
|
let dir = paths.sessions();
|
|
161
226
|
let mut removed = 0;
|
|
162
227
|
if let Ok(entries) = fs::read_dir(&dir) {
|
|
@@ -165,12 +230,16 @@ pub fn sweep(paths: &Paths) -> usize {
|
|
|
165
230
|
if path.extension().and_then(|e| e.to_str()) != Some("json") {
|
|
166
231
|
continue;
|
|
167
232
|
}
|
|
168
|
-
let
|
|
169
|
-
.
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
.
|
|
173
|
-
|
|
233
|
+
let dead = match fs::read_to_string(&path).ok().and_then(|text| serde_json::from_str::<Session>(&text).ok()) {
|
|
234
|
+
// Unparseable junk opens nothing; drop it.
|
|
235
|
+
None => true,
|
|
236
|
+
// Only this store's files are ours to judge. Another store's
|
|
237
|
+
// live token is none of our business.
|
|
238
|
+
Some(session) => {
|
|
239
|
+
session.store_id == current && (session.expired(now_ms()) || session.mac.is_none())
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
if dead && fs::remove_file(&path).is_ok() {
|
|
174
243
|
removed += 1;
|
|
175
244
|
}
|
|
176
245
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xiaolikt/ai-vault",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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.
|
|
36
|
+
"@xiaolikt/ai-vault-linux-x64": "0.7.0"
|
|
37
37
|
},
|
|
38
38
|
"files": [
|
|
39
39
|
"bin",
|
|
@@ -61,6 +61,10 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
|
|
|
61
61
|
|
|
62
62
|
所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
|
|
63
63
|
|
|
64
|
+
## 安全边界(一句话版)
|
|
65
|
+
|
|
66
|
+
模型的 `bash` 能找到会话令牌、能 `list`,但**签不出读取确认**(签名密钥只在插件进程内存里)、**改不了令牌文件**(带 HMAC,改了就作废)、**免费拿不到 `grant`**(要主密码)。详见仓库 README「安全」一节。
|
|
67
|
+
|
|
64
68
|
## 隔离
|
|
65
69
|
|
|
66
70
|
每个会话、每个子代理各自 `ai-vault unlock`,拿自己的令牌和读授权;父会话的解锁子代理继承不到。空闲 10 分钟自动失效,`/new`、`/fork`、退出会清掉本绑定的令牌。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-ai-vault",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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.
|
|
28
|
+
"@xiaolikt/ai-vault": "0.7.0"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* windows; a headless machine answers exit code 3 ("needs-ui") and the host
|
|
8
8
|
* dialog takes over here.
|
|
9
9
|
*/
|
|
10
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
10
11
|
import { spawn } from "node:child_process";
|
|
11
12
|
import { existsSync } from "node:fs";
|
|
12
13
|
import { homedir } from "node:os";
|
|
@@ -91,8 +92,54 @@ function message(stderr: string, fallback: string): string {
|
|
|
91
92
|
return lines[0]?.replace(/^ai-vault:\s*/, "") ?? fallback;
|
|
92
93
|
}
|
|
93
94
|
|
|
95
|
+
/**
|
|
96
|
+
* The secret this process keeps for the sessions it unlocked. It never reaches
|
|
97
|
+
* disk: the CLI writes it into the HMAC on each session file, and uses it to
|
|
98
|
+
* check the approvals we relay. A model-driven `bash` that finds a session
|
|
99
|
+
* token can therefore `list`, but can neither forge a read approval nor edit
|
|
100
|
+
* the token's grants.
|
|
101
|
+
*/
|
|
102
|
+
export class HostSecret {
|
|
103
|
+
#value: string | undefined;
|
|
104
|
+
|
|
105
|
+
get present(): boolean {
|
|
106
|
+
return this.#value !== undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Use the one the CLI echoed back at unlock time (it is ours already). */
|
|
110
|
+
adopt(secret: string | undefined): void {
|
|
111
|
+
if (secret && secret.length >= 32) this.#value = secret;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 32 fresh bytes, hex — minted once per process, before the first unlock. */
|
|
115
|
+
rotate(): string {
|
|
116
|
+
this.#value = randomBytes(32).toString("hex");
|
|
117
|
+
return this.#value;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The secret, minting it on first use. */
|
|
121
|
+
get value(): string {
|
|
122
|
+
return (this.#value ??= randomBytes(32).toString("hex"));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Environment for a CLI child: marks us as the host and passes the secret. */
|
|
126
|
+
env(): Record<string, string> {
|
|
127
|
+
return { AI_VAULT_HOST: "1", AI_VAULT_HOST_SECRET: this.value };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** HMAC over "allow:<token>:<entry>:<y|n>", what `get --answer-stdin` expects. */
|
|
131
|
+
approve(token: string, entry: string, answer: boolean): string | undefined {
|
|
132
|
+
if (!this.#value) return undefined;
|
|
133
|
+
return createHmac("sha256", this.#value)
|
|
134
|
+
.update(`allow:${token}:${entry.toLowerCase()}:${answer ? "y" : "n"}`)
|
|
135
|
+
.digest("hex");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
94
139
|
export class VaultCli {
|
|
95
140
|
readonly bin = resolveBinary();
|
|
141
|
+
/** Set by the extension at startup; the same secret for every binding. */
|
|
142
|
+
host = new HostSecret();
|
|
96
143
|
|
|
97
144
|
get available(): boolean {
|
|
98
145
|
return this.bin !== undefined;
|
|
@@ -112,7 +159,7 @@ export class VaultCli {
|
|
|
112
159
|
throw new CliError(EXIT.denied, undefined, "aborted", "");
|
|
113
160
|
}
|
|
114
161
|
const run = await new Promise<CliRun>((resolve, reject) => {
|
|
115
|
-
const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
162
|
+
const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...this.host.env() } });
|
|
116
163
|
let stdout = "";
|
|
117
164
|
let stderr = "";
|
|
118
165
|
const onAbort = () => child.kill("SIGKILL");
|
|
@@ -143,6 +190,16 @@ export class VaultCli {
|
|
|
143
190
|
return run;
|
|
144
191
|
}
|
|
145
192
|
|
|
193
|
+
/**
|
|
194
|
+
* `init` or `unlock`: returns the parsed result with the token, and keeps
|
|
195
|
+
* the host secret the CLI minted (or used ours) for later signing.
|
|
196
|
+
*/
|
|
197
|
+
async open<T extends { hostSecret?: string }>(subcommand: "init" | "unlock", args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
|
|
198
|
+
const result = await this.json<T>([subcommand, ...args], opts);
|
|
199
|
+
this.host.adopt(result.hostSecret);
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
|
|
146
203
|
/** One CLI call whose output is a JSON object. */
|
|
147
204
|
async json<T>(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
|
|
148
205
|
const run = await this.run([...args, "--json"], opts);
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
} from "./bitwarden.js";
|
|
25
25
|
import { CliError, VaultCli } from "./cli.js";
|
|
26
26
|
import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
|
|
27
|
-
import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
|
|
27
|
+
import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
|
|
28
28
|
import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
|
|
29
29
|
|
|
30
30
|
type Ctx = ExtensionToolContext | ExtensionCommandContext;
|
|
@@ -53,6 +53,8 @@ interface UnlockResult {
|
|
|
53
53
|
items: number;
|
|
54
54
|
mode?: UnlockModeName;
|
|
55
55
|
auto?: boolean;
|
|
56
|
+
/** Minted by the CLI for a host; kept in memory only, signs approvals. */
|
|
57
|
+
hostSecret?: string;
|
|
56
58
|
}
|
|
57
59
|
|
|
58
60
|
interface ListResult {
|
|
@@ -200,9 +202,9 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
200
202
|
}
|
|
201
203
|
}
|
|
202
204
|
const attempt = async (password?: string): Promise<UnlockResult> => {
|
|
203
|
-
const args = ["
|
|
205
|
+
const args = ["--requester", sessionLabel(ctx)];
|
|
204
206
|
if (password !== undefined) args.push("--password-stdin");
|
|
205
|
-
return cli.
|
|
207
|
+
return cli.open<UnlockResult>("unlock", args, {
|
|
206
208
|
stdin: password === undefined ? undefined : `${password}\n`,
|
|
207
209
|
signal,
|
|
208
210
|
});
|
|
@@ -356,7 +358,7 @@ async function bitwardenFallback(
|
|
|
356
358
|
const allow = await confirmWindow(
|
|
357
359
|
dialogs(ctx),
|
|
358
360
|
"pi-ai-vault · Bitwarden 里找到",
|
|
359
|
-
`本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
|
|
361
|
+
`本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`,
|
|
360
362
|
signal,
|
|
361
363
|
);
|
|
362
364
|
if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
|
|
@@ -365,7 +367,7 @@ async function bitwardenFallback(
|
|
|
365
367
|
const confirmed = await confirmWindow(
|
|
366
368
|
dialogs(ctx),
|
|
367
369
|
"pi-ai-vault · 导入到 ai-vault",
|
|
368
|
-
`把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
|
|
370
|
+
`把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
|
|
369
371
|
signal,
|
|
370
372
|
);
|
|
371
373
|
return confirmed ? importIt() : asValue("bitwarden-once");
|
|
@@ -405,11 +407,18 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
|
|
|
405
407
|
const allowed = await confirmWindow(
|
|
406
408
|
dialogs(ctx),
|
|
407
409
|
"ai-vault · 读取本地密码",
|
|
408
|
-
`条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
|
|
410
|
+
`条目: ${forDialog(params.name)}\n请求方: ${sub ? `子代理 ${forDialog(sub, 32)}` : "主会话"}\n原因: ${forDialog(params.reason ?? "(未说明)", 120)}\n\n` +
|
|
409
411
|
"允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
|
|
410
412
|
signal,
|
|
411
413
|
);
|
|
412
|
-
|
|
414
|
+
// Relaying is our privilege as the host: sign the answer under the
|
|
415
|
+
// host secret so the CLI can tell us from the model's own bash.
|
|
416
|
+
const token = scope.token ?? "";
|
|
417
|
+
const approval = cli.host.approve(token, params.name, allowed);
|
|
418
|
+
if (!approval) {
|
|
419
|
+
return fail("cannot relay an approval: no host secret for this session — run /vault unlock again");
|
|
420
|
+
}
|
|
421
|
+
const run = await cli.run([...base, "--json", "--answer-stdin", "--approval", approval], {
|
|
413
422
|
stdin: allowed ? "y\n" : "n\n",
|
|
414
423
|
signal,
|
|
415
424
|
});
|
|
@@ -532,16 +541,16 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
532
541
|
}
|
|
533
542
|
if (error.needsUi === "confirm") {
|
|
534
543
|
const meta = [
|
|
535
|
-
req.username?.trim() ? `用户名: ${req.username
|
|
536
|
-
req.uri?.trim() ? `URI: ${req.uri
|
|
537
|
-
req.notes?.trim() ? `备注: ${req.notes
|
|
544
|
+
req.username?.trim() ? `用户名: ${forDialog(req.username, 60)}` : "",
|
|
545
|
+
req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
|
|
546
|
+
req.notes?.trim() ? `备注: ${forDialog(req.notes, 120)}` : "",
|
|
538
547
|
]
|
|
539
548
|
.filter(Boolean)
|
|
540
549
|
.join("\n");
|
|
541
550
|
const ok = await confirmWindow(
|
|
542
551
|
dialogs(ctx),
|
|
543
552
|
"ai-vault · 保存到本地库",
|
|
544
|
-
`保存条目「${name}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
|
|
553
|
+
`保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
|
|
545
554
|
req.signal,
|
|
546
555
|
);
|
|
547
556
|
if (!ok) return `user denied saving "${name}"`;
|
|
@@ -658,7 +667,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
|
|
|
658
667
|
note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
|
|
659
668
|
};
|
|
660
669
|
try {
|
|
661
|
-
finish(await cli.
|
|
670
|
+
finish(await cli.open<UnlockResult>("init", ["--requester", label]));
|
|
662
671
|
return;
|
|
663
672
|
} catch (error) {
|
|
664
673
|
if (!(error instanceof CliError)) {
|
|
@@ -681,7 +690,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
|
|
|
681
690
|
return;
|
|
682
691
|
}
|
|
683
692
|
try {
|
|
684
|
-
finish(await cli.
|
|
693
|
+
finish(await cli.open<UnlockResult>("init", ["--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
|
|
685
694
|
} catch (error) {
|
|
686
695
|
note(ctx, `ai-vault: ${error instanceof CliError ? error.message : describe(error)}`, "error");
|
|
687
696
|
}
|
|
@@ -880,7 +889,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
880
889
|
note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
|
|
881
890
|
return;
|
|
882
891
|
}
|
|
883
|
-
const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${name}」?删除后无法恢复。`);
|
|
892
|
+
const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${forDialog(name)}」?删除后无法恢复。`);
|
|
884
893
|
if (!sure) return;
|
|
885
894
|
try {
|
|
886
895
|
const result = await cli.json<RemovingResult>([...args, "--yes"]);
|
|
@@ -906,7 +915,11 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
906
915
|
const args = ["grant", name, "--token", scope.token!];
|
|
907
916
|
if (minutes) args.push("--minutes", minutes);
|
|
908
917
|
try {
|
|
909
|
-
|
|
918
|
+
// A standing grant costs the master password, like a mode change.
|
|
919
|
+
const run = await cli.withPassword(args, () =>
|
|
920
|
+
promptSecret(dialogs(ctx), "ai-vault · 授权读取", "主密码(给这条条目 N 分钟免确认)"),
|
|
921
|
+
);
|
|
922
|
+
const result = JSON.parse(run.stdout) as { name: string; minutes: number };
|
|
910
923
|
setStatus(ctx, scope, "·granted");
|
|
911
924
|
note(ctx, `granted "${result.name}" for ${result.minutes}m`);
|
|
912
925
|
} catch (error) {
|
|
@@ -105,6 +105,19 @@ function failedToOpen(result: ZenityResult): boolean {
|
|
|
105
105
|
return result.stderr.split(/\r?\n/).some((line) => line.trim() !== "" && !gtkDiagnostic.test(line));
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Make a model-supplied value safe to put in a confirm window.
|
|
110
|
+
*
|
|
111
|
+
* The window is the one place the user reads what they are approving, so an
|
|
112
|
+
* entry name or reason that carries newlines could otherwise forge a whole
|
|
113
|
+
* second message ("请求方: 主会话 / 已授权, 点允许"). One line, bounded
|
|
114
|
+
* length, control characters gone.
|
|
115
|
+
*/
|
|
116
|
+
export function forDialog(value: string, max = 80): string {
|
|
117
|
+
const oneLine = value.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim();
|
|
118
|
+
return oneLine.length > max ? `${oneLine.slice(0, max - 1)}…` : oneLine;
|
|
119
|
+
}
|
|
120
|
+
|
|
108
121
|
/** Secret entry. Empty and cancel are both "no value". */
|
|
109
122
|
export async function promptSecret(
|
|
110
123
|
ctx: PromptHost | undefined,
|