@xiaolikt/ai-vault 0.4.1 → 0.6.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 +1 -1
- package/README.md +94 -12
- package/crates/ai-vault/Cargo.toml +1 -1
- package/crates/ai-vault/src/bwsession.rs +82 -0
- package/crates/ai-vault/src/cli.rs +364 -28
- package/crates/ai-vault/src/config.rs +171 -0
- package/crates/ai-vault/src/main.rs +2 -0
- package/crates/ai-vault/src/paths.rs +15 -0
- package/crates/ai-vault/src/session.rs +54 -4
- package/package.json +5 -5
- package/packages/pi-ai-vault/README.md +70 -0
- package/packages/pi-ai-vault/package.json +47 -0
- package/{src → packages/pi-ai-vault/src}/bitwarden.ts +62 -0
- package/{src → packages/pi-ai-vault/src}/cli.ts +21 -5
- package/{src → packages/pi-ai-vault/src}/index.ts +299 -51
- package/packages/pi-ai-vault/src/settings.ts +59 -0
- package/test/cli.sh +36 -0
- package/test/smoke.sh +2 -2
- package/tests/bitwarden-tools.test.mjs +1 -1
- package/tests/helpers.mjs +2 -0
- package/tests/import-map.test.mjs +1 -1
- package/tests/mocks/bin/zenity +9 -1
- package/tests/prompt.test.mjs +1 -1
- package/tests/register.test.mjs +1 -1
- package/tests/scrub.test.mjs +1 -1
- package/tests/vault-cli.test.mjs +152 -1
- /package/{src → packages/pi-ai-vault/src}/host.ts +0 -0
- /package/{src → packages/pi-ai-vault/src}/import-map.ts +0 -0
- /package/{src → packages/pi-ai-vault/src}/prompt.ts +0 -0
- /package/{src → packages/pi-ai-vault/src}/scrub.ts +0 -0
|
@@ -0,0 +1,171 @@
|
|
|
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.
|
|
7
|
+
|
|
8
|
+
use serde::{Deserialize, Serialize};
|
|
9
|
+
use std::fs;
|
|
10
|
+
|
|
11
|
+
use crate::crypto;
|
|
12
|
+
use crate::paths::Paths;
|
|
13
|
+
|
|
14
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
15
|
+
#[serde(rename_all = "kebab-case")]
|
|
16
|
+
pub enum UnlockMode {
|
|
17
|
+
/// Never ask again: the key lives in the store directory, readable by this
|
|
18
|
+
/// user, so agents can read secrets without any window.
|
|
19
|
+
Never,
|
|
20
|
+
/// Ask again after `hours`, counted from the unlock (not from the last use).
|
|
21
|
+
Time,
|
|
22
|
+
/// Ask once per agent session; the token dies when the session ends.
|
|
23
|
+
Session,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
impl UnlockMode {
|
|
27
|
+
pub fn parse(text: &str) -> Option<UnlockMode> {
|
|
28
|
+
match text.trim().to_lowercase().as_str() {
|
|
29
|
+
"never" | "no-password" | "none" | "off" => Some(UnlockMode::Never),
|
|
30
|
+
"time" | "hours" => Some(UnlockMode::Time),
|
|
31
|
+
"session" | "on" => Some(UnlockMode::Session),
|
|
32
|
+
_ => None,
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
pub fn as_str(self) -> &'static str {
|
|
37
|
+
match self {
|
|
38
|
+
UnlockMode::Never => "never",
|
|
39
|
+
UnlockMode::Time => "time",
|
|
40
|
+
UnlockMode::Session => "session",
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
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
|
+
|
|
75
|
+
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
|
76
|
+
pub struct UnlockPolicy {
|
|
77
|
+
pub mode: UnlockMode,
|
|
78
|
+
/// `Time` mode only: hours between password prompts.
|
|
79
|
+
#[serde(default = "default_hours")]
|
|
80
|
+
pub hours: i64,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
fn default_hours() -> i64 {
|
|
84
|
+
8
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
impl Default for UnlockPolicy {
|
|
88
|
+
fn default() -> Self {
|
|
89
|
+
UnlockPolicy { mode: UnlockMode::Session, hours: default_hours() }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
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)]
|
|
121
|
+
pub struct Config {
|
|
122
|
+
#[serde(default)]
|
|
123
|
+
pub unlock: UnlockPolicy,
|
|
124
|
+
#[serde(default)]
|
|
125
|
+
pub bitwarden: BitwardenPolicy,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/// A missing or unreadable config means the defaults. A broken file must not
|
|
129
|
+
/// lock anyone out of their vault.
|
|
130
|
+
pub fn load(paths: &Paths) -> Config {
|
|
131
|
+
match fs::read_to_string(paths.config()) {
|
|
132
|
+
Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
|
|
133
|
+
Err(_) => Config::default(),
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
pub fn save(paths: &Paths, config: &Config) -> Result<(), String> {
|
|
138
|
+
let bytes = serde_json::to_vec_pretty(config).map_err(|e| format!("cannot serialize config: {e}"))?;
|
|
139
|
+
crypto::write_atomic(&paths.config(), &bytes)
|
|
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,6 +32,21 @@ impl Paths {
|
|
|
32
32
|
self.dir.join("audit.log")
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/// Unlock policy (mode and, for `time`, the number of hours).
|
|
36
|
+
pub fn config(&self) -> PathBuf {
|
|
37
|
+
self.dir.join("config.json")
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// The machine-wide token `never` mode keeps, so no prompt is ever needed.
|
|
41
|
+
pub fn auto_session(&self) -> PathBuf {
|
|
42
|
+
self.dir.join("agent.session.json")
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/// The `bw` session key kept for `bitwarden.unlock = never | time`.
|
|
46
|
+
pub fn bw_session(&self) -> PathBuf {
|
|
47
|
+
self.dir.join("bitwarden.session.json")
|
|
48
|
+
}
|
|
49
|
+
|
|
35
50
|
/// Shared advisory lock for read-modify-write of the store file.
|
|
36
51
|
pub fn store_lock(&self) -> PathBuf {
|
|
37
52
|
self.dir.join("store.lock")
|
|
@@ -30,6 +30,10 @@ pub struct Session {
|
|
|
30
30
|
pub last_active: i64,
|
|
31
31
|
#[serde(rename = "idleMs")]
|
|
32
32
|
pub idle_ms: i64,
|
|
33
|
+
/// Absolute deadline, ms epoch. `None` means "no deadline": the token lives
|
|
34
|
+
/// until it is locked, its idle window passes, or the store changes.
|
|
35
|
+
#[serde(default, skip_serializing_if = "Option::is_none", rename = "expiresAt")]
|
|
36
|
+
pub expires_at: Option<i64>,
|
|
33
37
|
#[serde(rename = "storeId")]
|
|
34
38
|
pub store_id: String,
|
|
35
39
|
pub salt: String,
|
|
@@ -42,7 +46,7 @@ pub struct Session {
|
|
|
42
46
|
}
|
|
43
47
|
|
|
44
48
|
impl Session {
|
|
45
|
-
pub fn new(requester: &str, idle_ms: i64, store: &crypto::StoreFile, key: &[u8; 32]) -> Self {
|
|
49
|
+
pub fn new(requester: &str, idle_ms: i64, expires_at: Option<i64>, store: &crypto::StoreFile, key: &[u8; 32]) -> Self {
|
|
46
50
|
let now = now_ms();
|
|
47
51
|
Session {
|
|
48
52
|
token: crate::store::random_id() + &crate::store::random_id(),
|
|
@@ -50,6 +54,7 @@ impl Session {
|
|
|
50
54
|
created_at: now,
|
|
51
55
|
last_active: now,
|
|
52
56
|
idle_ms,
|
|
57
|
+
expires_at,
|
|
53
58
|
store_id: crypto::store_id(store),
|
|
54
59
|
salt: store.salt.clone(),
|
|
55
60
|
kdf: Some(store.kdf()),
|
|
@@ -68,12 +73,18 @@ impl Session {
|
|
|
68
73
|
Some(key)
|
|
69
74
|
}
|
|
70
75
|
|
|
76
|
+
/// A deadline beats the idle window; `idleMs: 0` with no deadline means
|
|
77
|
+
/// "never expires on its own".
|
|
71
78
|
pub fn expired(&self, now: i64) -> bool {
|
|
72
|
-
|
|
79
|
+
if let Some(deadline) = self.expires_at {
|
|
80
|
+
return now >= deadline;
|
|
81
|
+
}
|
|
82
|
+
self.idle_ms > 0 && now.saturating_sub(self.last_active) >= self.idle_ms
|
|
73
83
|
}
|
|
74
84
|
|
|
75
|
-
|
|
76
|
-
|
|
85
|
+
/// When this token stops working, if it does.
|
|
86
|
+
pub fn expiry(&self) -> Option<i64> {
|
|
87
|
+
self.expires_at.or_else(|| (self.idle_ms > 0).then_some(self.last_active + self.idle_ms))
|
|
77
88
|
}
|
|
78
89
|
|
|
79
90
|
/// Drop grants that ran out. Returns true when anything was removed.
|
|
@@ -167,6 +178,45 @@ pub fn sweep(paths: &Paths) -> usize {
|
|
|
167
178
|
removed
|
|
168
179
|
}
|
|
169
180
|
|
|
181
|
+
/// The machine-wide token used by `never` mode: no deadline, stored next to
|
|
182
|
+
/// the store so it survives reboots. Any process running as this user can read
|
|
183
|
+
/// it — that is the whole point of the mode.
|
|
184
|
+
pub fn load_auto(paths: &Paths) -> Result<Option<Session>, String> {
|
|
185
|
+
let path = paths.auto_session();
|
|
186
|
+
let text = match fs::read_to_string(&path) {
|
|
187
|
+
Ok(text) => text,
|
|
188
|
+
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
|
189
|
+
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
|
|
190
|
+
};
|
|
191
|
+
let session: Session = match serde_json::from_str(&text) {
|
|
192
|
+
Ok(session) => session,
|
|
193
|
+
Err(_) => {
|
|
194
|
+
let _ = fs::remove_file(&path);
|
|
195
|
+
return Ok(None);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
if session.expired(now_ms()) {
|
|
199
|
+
let _ = fs::remove_file(&path);
|
|
200
|
+
return Ok(None);
|
|
201
|
+
}
|
|
202
|
+
if session.key().is_none() {
|
|
203
|
+
let _ = fs::remove_file(&path);
|
|
204
|
+
return Ok(None);
|
|
205
|
+
}
|
|
206
|
+
Ok(Some(session))
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
pub fn save_auto(paths: &Paths, session: &Session) -> Result<(), String> {
|
|
210
|
+
fs::create_dir_all(&paths.dir).map_err(|e| format!("cannot create {}: {e}", paths.dir.display()))?;
|
|
211
|
+
let _ = fs::set_permissions(&paths.dir, fs::Permissions::from_mode(0o700));
|
|
212
|
+
let bytes = serde_json::to_vec(session).map_err(|e| format!("cannot serialize session: {e}"))?;
|
|
213
|
+
crypto::write_atomic(&paths.auto_session(), &bytes)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
pub fn delete_auto(paths: &Paths) -> bool {
|
|
217
|
+
fs::remove_file(paths.auto_session()).is_ok()
|
|
218
|
+
}
|
|
219
|
+
|
|
170
220
|
pub fn now_ms() -> i64 {
|
|
171
221
|
chrono::Utc::now().timestamp_millis()
|
|
172
222
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xiaolikt/ai-vault",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable) plus
|
|
3
|
+
"version": "0.6.0",
|
|
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",
|
|
7
7
|
"url": "git+https://github.com/xiaolikt/ai-vault.git"
|
|
@@ -33,12 +33,12 @@
|
|
|
33
33
|
"access": "public"
|
|
34
34
|
},
|
|
35
35
|
"optionalDependencies": {
|
|
36
|
-
"@xiaolikt/ai-vault-linux-x64": "0.
|
|
36
|
+
"@xiaolikt/ai-vault-linux-x64": "0.6.0"
|
|
37
37
|
},
|
|
38
38
|
"files": [
|
|
39
39
|
"bin",
|
|
40
|
-
"src",
|
|
41
40
|
"crates",
|
|
41
|
+
"packages",
|
|
42
42
|
"Cargo.toml",
|
|
43
43
|
"Cargo.lock",
|
|
44
44
|
"install.sh",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
},
|
|
72
72
|
"pi": {
|
|
73
73
|
"extensions": [
|
|
74
|
-
"./src/index.ts"
|
|
74
|
+
"./packages/pi-ai-vault/src/index.ts"
|
|
75
75
|
]
|
|
76
76
|
}
|
|
77
77
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# pi-ai-vault
|
|
2
|
+
|
|
3
|
+
ai-vault 的 pi 扩展——**omp 也能直接装同一个包**(omp 是 pi 的兼容分支,清单和工具 API 一致;差别只在 `src/host.ts` 的运行时探测里)。
|
|
4
|
+
|
|
5
|
+
它把本地加密密码库交给 [`ai-vault`](https://www.npmjs.com/package/@xiaolikt/ai-vault) 这个 Rust CLI:一台电脑一个库(`~/.ai-vault`),所有 agent 共用。插件本身不做加解密,只持有会话令牌。
|
|
6
|
+
|
|
7
|
+
## 安装
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pi install npm:pi-ai-vault # pi,自动带上 ai-vault CLI
|
|
11
|
+
omp plugin install npm:pi-ai-vault # omp,同一个包
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
然后在该宿主的会话里:
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
/vault init
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
(弹窗设主密码,两次。有桌面就开 zenity,没有就退回宿主自己的输入框。)
|
|
21
|
+
|
|
22
|
+
不想用 npm 也可以从仓库装:`pi install git:github.com/xiaolikt/ai-vault`。
|
|
23
|
+
|
|
24
|
+
## 工具
|
|
25
|
+
|
|
26
|
+
| 工具 | 作用 | 模型看到密码? |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| `vault_list` | 本地库条目元数据 | 否 |
|
|
29
|
+
| `vault_get` | 读一条:**先本地库,再 Bitwarden**;Bitwarden 命中会问「读一次 / 导入 ai-vault」 | 是,用户当场允许 |
|
|
30
|
+
| `vault_add` | 存一条;密码由用户在弹出的窗口里输入 | 否 |
|
|
31
|
+
| `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | 否 |
|
|
32
|
+
| `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | 在线 Bitwarden(`bw` CLI) | 否,`bw_reveal` 除外 |
|
|
33
|
+
| `bw_inject` | 注入 bash 环境(**仅 pi**,omp 不注册) | 否 |
|
|
34
|
+
|
|
35
|
+
## 命令
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
/vault init | unlock | lock | status | list | add | remove
|
|
39
|
+
/vault grant <名称> [分钟] | revoke <名称|all> | audit [n]
|
|
40
|
+
/vault import <bitwarden.json> | import-bw [搜索词]
|
|
41
|
+
/bw status|unlock|lock|clear
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## 解锁模式
|
|
45
|
+
|
|
46
|
+
本地库什么时候要主密码,由这台机器的模式决定(`/vault mode`,切换要主密码):
|
|
47
|
+
|
|
48
|
+
| 模式 | 行为 |
|
|
49
|
+
|---|---|
|
|
50
|
+
| `never` | 永远不问,读取也不弹确认窗——「agent 可以自由使用」的那批密码 |
|
|
51
|
+
| `time` | 解锁后 N 小时(默认 8)再问一次 |
|
|
52
|
+
| `session` | 每个会话一次,会话结束失效(默认) |
|
|
53
|
+
|
|
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
|
+
每个会话、每个子代理各自 `ai-vault unlock`,拿自己的令牌和读授权;父会话的解锁子代理继承不到。空闲 10 分钟自动失效,`/new`、`/fork`、退出会清掉本绑定的令牌。
|
|
67
|
+
|
|
68
|
+
完整说明(CLI 参数、退出码契约、Bitwarden 擦洗、审计、安全模型)见仓库 README:https://github.com/xiaolikt/ai-vault
|
|
69
|
+
|
|
70
|
+
MIT
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-ai-vault",
|
|
3
|
+
"version": "0.6.0",
|
|
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
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/xiaolikt/ai-vault.git"
|
|
8
|
+
},
|
|
9
|
+
"author": "xiaolikt",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"type": "module",
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=18"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"pi",
|
|
17
|
+
"pi-package",
|
|
18
|
+
"pi-coding-agent",
|
|
19
|
+
"omp",
|
|
20
|
+
"omp-package",
|
|
21
|
+
"ai-vault",
|
|
22
|
+
"vault",
|
|
23
|
+
"secrets",
|
|
24
|
+
"bitwarden",
|
|
25
|
+
"security"
|
|
26
|
+
],
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@xiaolikt/ai-vault": "0.6.0"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
32
|
+
"typebox": "1.3.27"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
36
|
+
"typebox": "1.3.27"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"src",
|
|
40
|
+
"README.md"
|
|
41
|
+
],
|
|
42
|
+
"pi": {
|
|
43
|
+
"extensions": [
|
|
44
|
+
"./src/index.ts"
|
|
45
|
+
]
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -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 ?? "");
|
|
@@ -779,6 +809,38 @@ export async function pullBitwardenLogins(
|
|
|
779
809
|
return filterLogins(bitwardenLogins(raw), search);
|
|
780
810
|
}
|
|
781
811
|
|
|
812
|
+
export type BitwardenLoginHit = { id: string; name: string; username: string; password: string; uris: string[] };
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* Look one login up by name/URI and return its password, with no window of its
|
|
816
|
+
* own: the caller shows the user what was found and asks whether to read it.
|
|
817
|
+
* `undefined` means "no such item"; an ambiguous reference throws with the
|
|
818
|
+
* candidates so the model can pick one.
|
|
819
|
+
*/
|
|
820
|
+
export async function lookupBitwardenLogin(
|
|
821
|
+
st: BwState,
|
|
822
|
+
ctx: ExtensionContext | undefined,
|
|
823
|
+
ref: string,
|
|
824
|
+
signal?: AbortSignal,
|
|
825
|
+
): Promise<BitwardenLoginHit | undefined> {
|
|
826
|
+
const session = await ensureUnlocked(st, ctx, signal);
|
|
827
|
+
let item: LiteItem;
|
|
828
|
+
try {
|
|
829
|
+
item = await resolveItem(st, session, ref, signal);
|
|
830
|
+
} catch (e) {
|
|
831
|
+
if (e instanceof Error && /^No Bitwarden item matches/.test(e.message)) return undefined;
|
|
832
|
+
throw e;
|
|
833
|
+
}
|
|
834
|
+
const secret = await secretOf(session, item, "password", signal);
|
|
835
|
+
return {
|
|
836
|
+
id: item.id ?? "",
|
|
837
|
+
name: item.name || "unnamed",
|
|
838
|
+
username: item.username,
|
|
839
|
+
password: secret.value,
|
|
840
|
+
uris: item.uri ? [item.uri] : [],
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
|
|
782
844
|
function normalizeEnvName(raw: string): string {
|
|
783
845
|
const name = raw.trim().toUpperCase();
|
|
784
846
|
if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) {
|
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
import { spawn } from "node:child_process";
|
|
11
11
|
import { existsSync } from "node:fs";
|
|
12
12
|
import { homedir } from "node:os";
|
|
13
|
-
import { delimiter, join } from "node:path";
|
|
13
|
+
import { delimiter, dirname, join } from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
14
15
|
|
|
15
16
|
export const EXIT = {
|
|
16
17
|
error: 1,
|
|
@@ -50,13 +51,28 @@ export class CliError extends Error {
|
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* `AI_VAULT_BIN`, then the copy this package depends on (npm puts the shim in
|
|
56
|
+
* a node_modules/.bin next to or above the plugin), then PATH, then the usual
|
|
57
|
+
* install spots.
|
|
58
|
+
*/
|
|
54
59
|
export function resolveBinary(): string | undefined {
|
|
55
60
|
const explicit = process.env.AI_VAULT_BIN;
|
|
56
61
|
if (explicit) return existsSync(explicit) ? explicit : undefined;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
62
|
+
|
|
63
|
+
// pip/npm layouts hoist differently: walk up from packages/pi-ai-vault/src.
|
|
64
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
65
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
66
|
+
const bundled = join(dir, "node_modules", ".bin", "ai-vault");
|
|
67
|
+
if (existsSync(bundled)) return bundled;
|
|
68
|
+
const parent = dirname(dir);
|
|
69
|
+
if (parent === dir) break;
|
|
70
|
+
dir = parent;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
for (const entry of (process.env.PATH ?? "").split(delimiter)) {
|
|
74
|
+
if (!entry) continue;
|
|
75
|
+
const candidate = join(entry, "ai-vault");
|
|
60
76
|
if (existsSync(candidate)) return candidate;
|
|
61
77
|
}
|
|
62
78
|
for (const candidate of [join(homedir(), ".local", "bin", "ai-vault"), join(homedir(), ".cargo", "bin", "ai-vault")]) {
|