@xiaolikt/ai-vault 0.5.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 +73 -11
- package/crates/ai-vault/Cargo.toml +2 -1
- package/crates/ai-vault/src/bwsession.rs +163 -0
- package/crates/ai-vault/src/cli.rs +380 -75
- package/crates/ai-vault/src/config.rs +99 -5
- package/crates/ai-vault/src/crypto.rs +34 -8
- package/crates/ai-vault/src/dialog.rs +45 -0
- package/crates/ai-vault/src/main.rs +1 -0
- package/crates/ai-vault/src/paths.rs +12 -0
- package/crates/ai-vault/src/session.rs +82 -13
- package/package.json +2 -2
- package/packages/pi-ai-vault/README.md +13 -1
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +30 -0
- package/packages/pi-ai-vault/src/cli.ts +58 -1
- package/packages/pi-ai-vault/src/index.ts +111 -54
- package/packages/pi-ai-vault/src/prompt.ts +13 -0
- package/packages/pi-ai-vault/src/settings.ts +59 -0
- package/test/cli.sh +106 -5
- package/tests/prompt.test.mjs +12 -0
- package/tests/vault-cli.test.mjs +98 -0
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
//! Machine-wide
|
|
2
|
-
//!
|
|
1
|
+
//! Machine-wide settings: when the vault asks for its master password, when
|
|
2
|
+
//! the Bitwarden side asks, and whether a Bitwarden hit may be imported
|
|
3
|
+
//! without asking.
|
|
4
|
+
//!
|
|
5
|
+
//! Stored in `<dir>/config.json` (0600, written atomically). A missing or
|
|
6
|
+
//! broken file means the defaults: ask once per session, offer imports.
|
|
3
7
|
|
|
4
8
|
use serde::{Deserialize, Serialize};
|
|
5
9
|
use std::fs;
|
|
@@ -38,6 +42,36 @@ impl UnlockMode {
|
|
|
38
42
|
}
|
|
39
43
|
}
|
|
40
44
|
|
|
45
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
46
|
+
#[serde(rename_all = "lowercase")]
|
|
47
|
+
pub enum ImportPolicy {
|
|
48
|
+
/// Show the Bitwarden hit, read it once, then ask whether to import it.
|
|
49
|
+
Ask,
|
|
50
|
+
/// Import whatever is found and hand it back: no window at all.
|
|
51
|
+
Always,
|
|
52
|
+
/// Never write a Bitwarden entry into the store; read one-offs only.
|
|
53
|
+
Never,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
impl ImportPolicy {
|
|
57
|
+
pub fn parse(text: &str) -> Option<ImportPolicy> {
|
|
58
|
+
match text.trim().to_lowercase().as_str() {
|
|
59
|
+
"ask" | "confirm" => Some(ImportPolicy::Ask),
|
|
60
|
+
"always" | "auto" | "yes" => Some(ImportPolicy::Always),
|
|
61
|
+
"never" | "no" | "off" => Some(ImportPolicy::Never),
|
|
62
|
+
_ => None,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
pub fn as_str(self) -> &'static str {
|
|
67
|
+
match self {
|
|
68
|
+
ImportPolicy::Ask => "ask",
|
|
69
|
+
ImportPolicy::Always => "always",
|
|
70
|
+
ImportPolicy::Never => "never",
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
41
75
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
|
42
76
|
pub struct UnlockPolicy {
|
|
43
77
|
pub mode: UnlockMode,
|
|
@@ -56,14 +90,43 @@ impl Default for UnlockPolicy {
|
|
|
56
90
|
}
|
|
57
91
|
}
|
|
58
92
|
|
|
59
|
-
#[derive(Debug, Clone, Serialize, Deserialize
|
|
93
|
+
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
|
94
|
+
pub struct BitwardenPolicy {
|
|
95
|
+
/// `never` keeps the `bw` session key in the store directory, so no
|
|
96
|
+
/// Bitwarden master password is asked; `time` does the same with a
|
|
97
|
+
/// deadline; `session` (default) keeps it in the agent's memory only.
|
|
98
|
+
#[serde(default = "default_bw_mode")]
|
|
99
|
+
pub unlock: UnlockMode,
|
|
100
|
+
#[serde(default = "default_hours")]
|
|
101
|
+
pub hours: i64,
|
|
102
|
+
#[serde(default = "default_import")]
|
|
103
|
+
pub import: ImportPolicy,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
fn default_bw_mode() -> UnlockMode {
|
|
107
|
+
UnlockMode::Session
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
fn default_import() -> ImportPolicy {
|
|
111
|
+
ImportPolicy::Ask
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
impl Default for BitwardenPolicy {
|
|
115
|
+
fn default() -> Self {
|
|
116
|
+
BitwardenPolicy { unlock: default_bw_mode(), hours: default_hours(), import: default_import() }
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
|
|
60
121
|
pub struct Config {
|
|
61
122
|
#[serde(default)]
|
|
62
123
|
pub unlock: UnlockPolicy,
|
|
124
|
+
#[serde(default)]
|
|
125
|
+
pub bitwarden: BitwardenPolicy,
|
|
63
126
|
}
|
|
64
127
|
|
|
65
|
-
/// A missing or unreadable config means the
|
|
66
|
-
///
|
|
128
|
+
/// A missing or unreadable config means the defaults. A broken file must not
|
|
129
|
+
/// lock anyone out of their vault.
|
|
67
130
|
pub fn load(paths: &Paths) -> Config {
|
|
68
131
|
match fs::read_to_string(paths.config()) {
|
|
69
132
|
Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
|
|
@@ -75,3 +138,34 @@ pub fn save(paths: &Paths, config: &Config) -> Result<(), String> {
|
|
|
75
138
|
let bytes = serde_json::to_vec_pretty(config).map_err(|e| format!("cannot serialize config: {e}"))?;
|
|
76
139
|
crypto::write_atomic(&paths.config(), &bytes)
|
|
77
140
|
}
|
|
141
|
+
|
|
142
|
+
#[cfg(test)]
|
|
143
|
+
mod tests {
|
|
144
|
+
use super::*;
|
|
145
|
+
|
|
146
|
+
#[test]
|
|
147
|
+
fn parses_aliases() {
|
|
148
|
+
assert_eq!(UnlockMode::parse("no-password"), Some(UnlockMode::Never));
|
|
149
|
+
assert_eq!(UnlockMode::parse("SESSION"), Some(UnlockMode::Session));
|
|
150
|
+
assert_eq!(UnlockMode::parse("2h"), None);
|
|
151
|
+
assert_eq!(ImportPolicy::parse("auto"), Some(ImportPolicy::Always));
|
|
152
|
+
assert_eq!(ImportPolicy::parse("off"), Some(ImportPolicy::Never));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#[test]
|
|
156
|
+
fn defaults_are_the_cautious_ones() {
|
|
157
|
+
let config = Config::default();
|
|
158
|
+
assert_eq!(config.unlock.mode, UnlockMode::Session);
|
|
159
|
+
assert_eq!(config.bitwarden.unlock, UnlockMode::Session);
|
|
160
|
+
assert_eq!(config.bitwarden.import, ImportPolicy::Ask);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
#[test]
|
|
164
|
+
fn old_configs_still_load() {
|
|
165
|
+
// A config written by the previous version had only `unlock`.
|
|
166
|
+
let parsed: Config = serde_json::from_str(r#"{"unlock":{"mode":"time","hours":4}}"#).unwrap();
|
|
167
|
+
assert_eq!(parsed.unlock.mode, UnlockMode::Time);
|
|
168
|
+
assert_eq!(parsed.bitwarden.import, ImportPolicy::Ask);
|
|
169
|
+
assert_eq!(parsed.bitwarden.hours, 8);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -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,6 +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`,
|
|
46
|
+
/// sealed under `wrap_key`.
|
|
47
|
+
pub fn bw_session(&self) -> PathBuf {
|
|
48
|
+
self.dir.join("bitwarden.session.json")
|
|
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
|
+
|
|
45
57
|
/// Shared advisory lock for read-modify-write of the store file.
|
|
46
58
|
pub fn store_lock(&self) -> PathBuf {
|
|
47
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",
|
|
@@ -51,7 +51,19 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
|
|
|
51
51
|
| `time` | 解锁后 N 小时(默认 8)再问一次 |
|
|
52
52
|
| `session` | 每个会话一次,会话结束失效(默认) |
|
|
53
53
|
|
|
54
|
-
`vault_get` 找不到本地条目时会去 Bitwarden
|
|
54
|
+
`vault_get` 找不到本地条目时会去 Bitwarden 搜;命中后按 `bitwarden.import` 处理:
|
|
55
|
+
|
|
56
|
+
| `bitwarden.import` | 行为 |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `ask`(默认) | 给你看这一条 → 读一次 → 问「导入 ai-vault / 只用这一次」 |
|
|
59
|
+
| `always` | 命中直接导入并返回,不开窗口 |
|
|
60
|
+
| `never` | 只读一次,永不写入本地库 |
|
|
61
|
+
|
|
62
|
+
所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
|
|
63
|
+
|
|
64
|
+
## 安全边界(一句话版)
|
|
65
|
+
|
|
66
|
+
模型的 `bash` 能找到会话令牌、能 `list`,但**签不出读取确认**(签名密钥只在插件进程内存里)、**改不了令牌文件**(带 HMAC,改了就作废)、**免费拿不到 `grant`**(要主密码)。详见仓库 README「安全」一节。
|
|
55
67
|
|
|
56
68
|
## 隔离
|
|
57
69
|
|
|
@@ -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",
|
|
@@ -55,6 +55,7 @@ import { Type } from "typebox";
|
|
|
55
55
|
import { bitwardenLogins, filterLogins, type LoginDraft } from "./import-map.js";
|
|
56
56
|
import { onSessionLeave, sessionLabel, withTier } from "./host.js";
|
|
57
57
|
import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
|
|
58
|
+
import { getSettingsSafe, settingsCli } from "./settings.js";
|
|
58
59
|
import { scrubDeep, scrubText } from "./scrub.js";
|
|
59
60
|
|
|
60
61
|
// ---------------------------------------------------------------------------
|
|
@@ -492,6 +493,9 @@ function startAutoLock(st: BwState, ctx: ExtensionContext | undefined): void {
|
|
|
492
493
|
/** Drop this binding's session key and injected variables, and the clipboard. */
|
|
493
494
|
async function lock(st: BwState, reason: string): Promise<void> {
|
|
494
495
|
const hadSession = !!st.key;
|
|
496
|
+
// A key kept for `bitwarden.unlock = never | time` must go with an explicit
|
|
497
|
+
// lock, or the next call would silently unlock again.
|
|
498
|
+
void settingsCli().run(["bw-session", "clear"]).catch(() => undefined);
|
|
495
499
|
st.epoch++;
|
|
496
500
|
st.key = undefined;
|
|
497
501
|
st.verifiedAt = 0;
|
|
@@ -545,6 +549,27 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
|
|
|
545
549
|
|
|
546
550
|
const epoch = st.epoch;
|
|
547
551
|
const pending = (async () => {
|
|
552
|
+
const policy = (await getSettingsSafe(signal)).bitwarden;
|
|
553
|
+
// `never` / `time`: the CLI keeps the session key (0600, in the store
|
|
554
|
+
// directory), so Bitwarden costs no window at all.
|
|
555
|
+
if (policy.unlock !== "session") {
|
|
556
|
+
try {
|
|
557
|
+
const saved = await settingsCli().json<{ key: string }>(["bw-session", "get"], { signal });
|
|
558
|
+
if (saved?.key) {
|
|
559
|
+
const verify = await bwStatus(saved.key, signal);
|
|
560
|
+
if (verify?.status === "unlocked") {
|
|
561
|
+
st.key = saved.key;
|
|
562
|
+
st.verifiedAt = Date.now();
|
|
563
|
+
acquireSessionKey();
|
|
564
|
+
startAutoLock(st, ctx);
|
|
565
|
+
return saved.key;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
} catch {
|
|
569
|
+
/* absent or expired: fall through to the password */
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
548
573
|
const status = await bwStatus(undefined, signal); // no session env
|
|
549
574
|
if (status?.status === "unauthenticated") throw new Error(BW_LOGIN_HINT);
|
|
550
575
|
|
|
@@ -569,6 +594,11 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
|
|
|
569
594
|
st.verifiedAt = Date.now();
|
|
570
595
|
acquireSessionKey();
|
|
571
596
|
startAutoLock(st, ctx);
|
|
597
|
+
if (policy.unlock !== "session") {
|
|
598
|
+
// Keep the key where the CLI can hand it back; the file's expiry comes
|
|
599
|
+
// from the bitwarden.hours policy.
|
|
600
|
+
await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
|
|
601
|
+
}
|
|
572
602
|
await audit("unlock", "ok", st.sessionLabel);
|
|
573
603
|
// Refresh in the background: a full sync can take seconds on large vaults.
|
|
574
604
|
const lastSync = Date.parse(status?.lastSync ?? "");
|
|
@@ -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);
|