@xiaolikt/ai-vault 0.6.0 → 0.8.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 +78 -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 +10 -0
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +12 -9
- package/packages/pi-ai-vault/src/cli.ts +58 -1
- package/packages/pi-ai-vault/src/ente.ts +278 -0
- package/packages/pi-ai-vault/src/index.ts +31 -15
- package/packages/pi-ai-vault/src/prompt.ts +13 -0
- package/test/cli.sh +85 -5
- package/tests/ente.test.mjs +86 -0
- package/tests/helpers.mjs +2 -0
- package/tests/mocks/bin/ente +61 -0
- package/tests/prompt.test.mjs +12 -0
- package/tests/register.test.mjs +5 -1
- 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.8.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.8.0"
|
|
37
37
|
},
|
|
38
38
|
"files": [
|
|
39
39
|
"bin",
|
|
@@ -31,6 +31,8 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
|
|
|
31
31
|
| `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | 否 |
|
|
32
32
|
| `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | 在线 Bitwarden(`bw` CLI) | 否,`bw_reveal` 除外 |
|
|
33
33
|
| `bw_inject` | 注入 bash 环境(**仅 pi**,omp 不注册) | 否 |
|
|
34
|
+
| `ente_list` | Ente Auth 条目元数据 | 否 |
|
|
35
|
+
| `ente_code` | 当前 TOTP/Steam 验证码(每次确认) | 是,用户当场允许 |
|
|
34
36
|
|
|
35
37
|
## 命令
|
|
36
38
|
|
|
@@ -61,6 +63,14 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
|
|
|
61
63
|
|
|
62
64
|
所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
|
|
63
65
|
|
|
66
|
+
## Ente
|
|
67
|
+
|
|
68
|
+
`ente` CLI 自己登录一次(`ente account login --app auth`),插件只是它的客户端:`ente_list` 只给元数据,`ente_code` 每次弹窗确认。详见仓库 README。
|
|
69
|
+
|
|
70
|
+
## 安全边界(一句话版)
|
|
71
|
+
|
|
72
|
+
模型的 `bash` 能找到会话令牌、能 `list`,但**签不出读取确认**(签名密钥只在插件进程内存里)、**改不了令牌文件**(带 HMAC,改了就作废)、**免费拿不到 `grant`**(要主密码)。详见仓库 README「安全」一节。
|
|
73
|
+
|
|
64
74
|
## 隔离
|
|
65
75
|
|
|
66
76
|
每个会话、每个子代理各自 `ai-vault unlock`,拿自己的令牌和读授权;父会话的解锁子代理继承不到。空闲 10 分钟自动失效,`/new`、`/fork`、退出会清掉本绑定的令牌。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-ai-vault",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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.8.0"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
@@ -354,7 +354,7 @@ const AUDIT_MAX_BYTES = 1024 * 1024;
|
|
|
354
354
|
let auditModeFixed = false;
|
|
355
355
|
|
|
356
356
|
/** One audit line per event. `session` is the binding's label, so a subagent's `bw_run` can be told from its parent's. */
|
|
357
|
-
async function
|
|
357
|
+
export async function auditEvent(event: string, detail: string, session?: string): Promise<void> {
|
|
358
358
|
try {
|
|
359
359
|
await fs.mkdir(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
360
360
|
const log = path.join(STATE_DIR, "audit.log");
|
|
@@ -513,7 +513,7 @@ async function lock(st: BwState, reason: string): Promise<void> {
|
|
|
513
513
|
st.lockTimer = undefined;
|
|
514
514
|
}
|
|
515
515
|
if (hadSession) {
|
|
516
|
-
await
|
|
516
|
+
await auditEvent("lock", `reason=${reason}`, st.sessionLabel);
|
|
517
517
|
if (!releaseSessionKey()) return; // another binding still uses its own key
|
|
518
518
|
try {
|
|
519
519
|
const bin = await resolveBw();
|
|
@@ -581,7 +581,7 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
|
|
|
581
581
|
signal,
|
|
582
582
|
});
|
|
583
583
|
if (r.code !== 0) {
|
|
584
|
-
await
|
|
584
|
+
await auditEvent("unlock", "deny=bad-password", st.sessionLabel);
|
|
585
585
|
throw new Error(`Unlock failed (wrong master password or CLI error). ${tail(r.stderr, 120)}`);
|
|
586
586
|
}
|
|
587
587
|
const key = r.stdout.replace(/[\r\n]+$/, "");
|
|
@@ -599,7 +599,7 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
|
|
|
599
599
|
// from the bitwarden.hours policy.
|
|
600
600
|
await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
|
|
601
601
|
}
|
|
602
|
-
await
|
|
602
|
+
await auditEvent("unlock", "ok", st.sessionLabel);
|
|
603
603
|
// Refresh in the background: a full sync can take seconds on large vaults.
|
|
604
604
|
const lastSync = Date.parse(status?.lastSync ?? "");
|
|
605
605
|
if (!Number.isFinite(lastSync) || Date.now() - lastSync > 15 * 60_000) {
|
|
@@ -750,7 +750,7 @@ async function approveItem(
|
|
|
750
750
|
const user = item.username ? ` (user: ${item.username})` : "";
|
|
751
751
|
const ok = await confirmAction(ctx, title, `Item: ${name}${user}\nField: ${field}\n${detail}\n\nAllow?`, signal);
|
|
752
752
|
if (!ok) {
|
|
753
|
-
await
|
|
753
|
+
await auditEvent(event, `deny item="${name}" field=${field}`, st.sessionLabel);
|
|
754
754
|
return undefined;
|
|
755
755
|
}
|
|
756
756
|
return { session, item };
|
|
@@ -1116,6 +1116,9 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
|
|
|
1116
1116
|
spawnHook: ({ command, cwd, env }) => {
|
|
1117
1117
|
// A BW_SESSION exported in the user's shell must not reach bash.
|
|
1118
1118
|
for (const name of Object.keys(env)) if (name.startsWith("BW_")) delete env[name];
|
|
1119
|
+
// Same for Ente's unattended vault key / export password: the model's
|
|
1120
|
+
// shell must not be able to open Ente Auth with what the user exported.
|
|
1121
|
+
for (const name of ["ENTE_CLI_VAULT_KEY", "ENTE_CLI_PASSWORD"]) delete env[name];
|
|
1119
1122
|
for (const [name, rec] of st.injected) env[name] = rec.value;
|
|
1120
1123
|
return { command, cwd, env };
|
|
1121
1124
|
},
|
|
@@ -1230,7 +1233,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
|
|
|
1230
1233
|
const { value, itemId, itemName } = await secretOf(approved.session, approved.item, field, signal);
|
|
1231
1234
|
st.injected.set(envName, { value, item: itemName, field, at: Date.now() });
|
|
1232
1235
|
rememberScrubValue(envName, value);
|
|
1233
|
-
await
|
|
1236
|
+
await auditEvent("inject", `allow env=${envName} item="${itemName}" (${itemId}) field=${field}`, st.sessionLabel);
|
|
1234
1237
|
safeStatus(ctx, `🔓 bw: ${st.injected.size} env var(s)`);
|
|
1235
1238
|
const weak =
|
|
1236
1239
|
value.length < 6
|
|
@@ -1303,7 +1306,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
|
|
|
1303
1306
|
signal,
|
|
1304
1307
|
group: true,
|
|
1305
1308
|
});
|
|
1306
|
-
await
|
|
1309
|
+
await auditEvent("run", `allow env=${envName} item="${itemName}" field=${field} exit=${r.code}`, st.sessionLabel);
|
|
1307
1310
|
const raw = [r.stdout, r.stderr].filter((s) => s.length > 0).join("\n");
|
|
1308
1311
|
const scrubbed = scrubText(raw, scrubValues.values()).text;
|
|
1309
1312
|
const output =
|
|
@@ -1356,7 +1359,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
|
|
|
1356
1359
|
// so tool output carrying it must be scrubbed like an injected var.
|
|
1357
1360
|
rememberScrubValue("CLIPBOARD", value);
|
|
1358
1361
|
await copyToClipboard(value);
|
|
1359
|
-
await
|
|
1362
|
+
await auditEvent("clipboard", `allow item="${itemName}" field=${field}`, st.sessionLabel);
|
|
1360
1363
|
const clears =
|
|
1361
1364
|
CONFIG.clipboardClearSeconds > 0 ? `Clears in ${CONFIG.clipboardClearSeconds}s.` : "Auto-clear disabled.";
|
|
1362
1365
|
return {
|
|
@@ -1401,7 +1404,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
|
|
|
1401
1404
|
);
|
|
1402
1405
|
if (!approved) throw new Error("User declined the reveal.");
|
|
1403
1406
|
const { value, itemName } = await secretOf(approved.session, approved.item, field, signal);
|
|
1404
|
-
await
|
|
1407
|
+
await auditEvent("reveal", `allow item="${itemName}" field=${field}`, st.sessionLabel);
|
|
1405
1408
|
return {
|
|
1406
1409
|
content: [{ type: "text", text: `${itemName} (${field}):\n<secret>${value}</secret>` }],
|
|
1407
1410
|
details: { item: itemName, field },
|
|
@@ -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);
|