@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 CHANGED
@@ -14,13 +14,14 @@ dependencies = [
14
14
 
15
15
  [[package]]
16
16
  name = "ai-vault"
17
- version = "0.6.0"
17
+ version = "0.8.0"
18
18
  dependencies = [
19
19
  "base64",
20
20
  "chacha20poly1305",
21
21
  "chrono",
22
22
  "clap",
23
23
  "getrandom",
24
+ "hmac",
24
25
  "libc",
25
26
  "scrypt",
26
27
  "serde",
package/README.md CHANGED
@@ -94,7 +94,8 @@ ai-vault [--dir DIR] [--json] <命令>
94
94
  | `unlock [--password-stdin] [--requester ID]` | 按当前模式解锁,stdout 一个令牌 |
95
95
  | `mode [get]` / `mode set never\|time\|session [--hours N]` | 查看/切换解锁模式(切换要主密码) |
96
96
  | `settings [键] [值]` | 全部设置:`vault.unlock` `vault.hours` `bitwarden.unlock` `bitwarden.hours` `bitwarden.import` |
97
- | `bw-session get\|put\|clear` | Bitwarden 会话密钥的落盘副本(`bitwarden.unlock != session` 时用) |
97
+ | `bw-session get\|put\|clear` | Bitwarden 会话密钥的落盘副本(`bitwarden.unlock != session` 时用,加密封存) |
98
+ | `rekey` | 把旧库的 scrypt 参数升到当前默认(要主密码) |
98
99
  | `status --token T` | 条目数、过期时间、还活着的读授权 |
99
100
  | `lock --token T \| --all` | 丢掉令牌(`--all` 清空本机所有会话) |
100
101
  | `list --token T` | 条目元数据(名称/用户名/URI),没有密码 |
@@ -119,7 +120,18 @@ ai-vault [--dir DIR] [--json] <命令>
119
120
  | 4 | 用户拒绝/取消 | **不要重试**,问用户 |
120
121
  | 5 | 未解锁 / 密码错 | 重新 `unlock`,或提示主密码错误 |
121
122
 
122
- 所以「没有桌面的机器」也能用:`unlock --password-stdin`、`get --answer-stdin`、`add --password-stdin --yes`、`save --yes` 就是无界面路径。
123
+ 所以「没有桌面的机器」也能用:`unlock --password-stdin`、`add --password-stdin --yes`、`save --yes` 就是无界面路径。
124
+
125
+ **转发确认是宿主特权**,需要三样东西同时成立:
126
+
127
+ ```bash
128
+ AI_VAULT_HOST=1 \
129
+ AI_VAULT_HOST_SECRET=<unlock 时返回的 hostSecret> \
130
+ ai-vault get <条目> --token <T> --answer-stdin --approval <hex> <<< 'y'
131
+ # approval = HMAC-SHA256(hostSecret, "allow:<T>:<条目小写>:y")
132
+ ```
133
+
134
+ `unlock`/`init` 只在 `AI_VAULT_HOST=1` 时返回 `hostSecret`;它只存在于宿主进程内存里,CLI 用它给会话文件签名、用它核对转发。少了任何一样,`--answer-stdin` 都是退出码 2。这就是为什么模型的 `bash` 即使拿到令牌也签不出「允许」。
123
135
 
124
136
  ## 插件里的工具
125
137
 
@@ -134,6 +146,8 @@ ai-vault [--dir DIR] [--json] <命令>
134
146
  | `bw_inject` | 注入 bash 环境(**仅 pi**) | exec | 否 |
135
147
  | `bw_clipboard` | 复制到剪贴板,到时清除 | write | 否 |
136
148
  | `bw_reveal` | 明文返回(默认关闭,每次确认) | exec | 是,用户当场允许 |
149
+ | `ente_list` | Ente Auth 条目元数据(名称/签发方/账号/类型) | read | 否 |
150
+ | `ente_code` | 读一条当前 TOTP/Steam 验证码,每次弹窗确认 | write | 是,用户当场允许 |
137
151
 
138
152
  字段选择:`password`(默认)· `totp`(种子)· `code`(动态验证码)· `notes` · `field:<自定义字段名>`。
139
153
 
@@ -217,7 +231,7 @@ ai-vault settings bitwarden.hours 24
217
231
  ## 会话与隔离
218
232
 
219
233
  - 每个绑定(一个会话,或一个子代理)在第一次用到库时各自 `ai-vault unlock`,拿到**自己的令牌**。父会话的解锁和授权子代理继承不到;确认窗口里会写「请求方: 子代理 0-Explore」。
220
- - 令牌寿命由解锁模式决定(见上):`session` 到会话结束、`time` 到 N 小时、`never` 不过期。`/new`、`/fork`、退出会让插件把自己的令牌删掉;`/resume` 保留。
234
+ - 令牌寿命由解锁模式决定(见上):`session` 最长 24 小时、`time` 到 N 小时、`never` 不过期。`/new`、`/fork`、退出会让插件把自己的令牌删掉;`/resume` 保留。失效、被改、属于旧库的令牌文件在**每次** CLI 调用时都会被清掉。
221
235
  - 读授权存在令牌里,所以天然按请求方隔离;`/vault grant`、`/vault revoke` 改的就是它。
222
236
  - 库文件本身共享:读改写有 `flock`,两个 agent 同时写不会丢更新(旧版是后写覆盖先写)。
223
237
 
@@ -232,16 +246,69 @@ ai-vault settings bitwarden.hours 24
232
246
  - `/bw lock` 只丢弃当前绑定的会话密钥;同一进程里还有别的绑定持有时不会执行全局 `bw lock`,最后一个绑定释放时才真正作废 CLI 会话。
233
247
  - Bitwarden 会话密钥只在 agent 进程内存里,不落盘、不进 bash 环境。
234
248
 
249
+ ## Ente(Auth 验证码)
250
+
251
+ `ente` 是 Ente 官方的终端客户端(0.4+)。它**自己登录一次**:
252
+
253
+ ```bash
254
+ ente account login --app auth # 邮箱 + 密码(+ 2FA 验证码)
255
+ ente auth code list # 之后每次都不再问密码
256
+ ```
257
+
258
+ 会话存在 `$XDG_DATA_HOME/ente-cli`(Linux 默认 `~/.local/share/ente-cli`),数据库密钥默认放系统钥匙串;无桌面/无人值守时用
259
+
260
+ ```bash
261
+ ente vault key generate # 打印一个 key
262
+ export ENTE_CLI_VAULT_KEY=<那个 key> # 之后连钥匙串都不用
263
+ ```
264
+
265
+ 所以在 `session` 这种日常形态下,**每次查看不会再要你的密码**,最多要一次系统钥匙串解锁。
266
+
267
+ pi-ai-vault 只是这套 CLI 的客户端,本身不保存 Ente 的任何密钥:
268
+
269
+ | 工具 | 作用 |
270
+ |---|---|
271
+ | `ente_list` | 列出条目(name / issuer / accountName / type),**不含验证码** |
272
+ | `ente_code <名字>` | 弹窗显示实际命中的条目,允许后返回当前验证码和过期时间 |
273
+
274
+ 安全上和 `bw_*` 一套规则:列表只给元数据;读码每次确认;拒绝后不重试;允许/拒绝都写审计(`~/.bw/pi-extension/audit.log`,`ente.code` 事件,不含码本身);条目名/签发方进窗口前会被压成一行,防伪造。
275
+
276
+ 插件启动的 bash 会剔除 `ENTE_CLI_VAULT_KEY` / `ENTE_CLI_PASSWORD`,避免你 shell 里导出的免密 key 漏进模型自己的命令环境。**注意**:`ente` 二进制本身也在 PATH 上,模型直接跑 `ente auth code view` 仍能绕过这个扩展的确认窗——要收紧要靠 `ENTE_CLI_VAULT_KEY` + 把模型的 `ENTE_CLI_HOME` 指到别处,或者干脆不让 agent 有 shell。
277
+
235
278
  ## 安全
236
279
 
237
- - 主密码只经过弹窗或宿主输入框;`unlock` 派生出的 key 只写进令牌文件(0600,优先 tmpfs,登出即消失)。`never` 模式例外:key 写在 `~/.ai-vault/agent.session.json`,跨重启存在——这是那个模式的定义,不是疏漏。Bitwarden 侧同理:`bitwarden.unlock = never|time` 会把 `bw` 会话密钥写到 `~/.ai-vault/bitwarden.session.json`(0600),它是 bearer token,丢了等于丢了那次登录。它和「agent 进程内存里有 key」是同一级别的暴露面,好处是换会话、reload、崩溃都会自然清掉。
238
- - 会话令牌只是 id,不是 key:泄露令牌不等于泄露密码,但仍能读库,所以 `lock` 要真删文件。
239
- - 插件启动的子进程(`bw`、`bw_run` 的 bash、剪贴板工具)都会剔除宿主环境里的 `BW_*`,避免用户 shell 里导出的会话密钥漏进命令环境。
240
- - 审计:`~/.ai-vault/audit.log` 记录会话/子代理标签、条目名、允许/拒绝,从不记录值;写失败不影响主操作;1 MiB 轮转成 `.1`。
241
- - `bw_reveal` 默认关闭;要明文通道得在配置里显式打开。
242
- - 擦洗只在值长度 ≥ 6 时生效(更短的会误伤正常输出);网络外传、单向哈希防不住——`bw_run` / `bw_inject` 的价值是值不进对话,不是防住被注入的 agent。
243
- - 原子写:临时文件(0600、唯一命名)+ `fsync` + `rename` + 目录 `fsync`;KDF 参数写在文件头,以后调参不会毁老库。
244
- - 库格式和旧版 `omp-vault` 完全一致(`v:1`、`salt`、`kdf{N,r,p}`、`ct = base64(iv‖ct‖tag)`),主密码不变,Node 和 Rust 两边都验证过互读。
280
+ ### 威胁模型:谁能做什么
281
+
282
+ 所有东西都跑在**你的用户**下,所以边界不是「用户 vs 别人」,而是**你(人)vs 跑在你账号下的 agent**。设计目标是:agent 可以*用*密码,但不能*绕过你*去拿。
283
+
284
+ | 角色 | 能 | 不能 |
285
+ |---|---|---|
286
+ | **你**(终端里手敲 `ai-vault`) | 一切 | — |
287
+ | **宿主**(pi/omp 扩展进程,持 `AI_VAULT_HOST=1` + 内存里的 host secret) | 替你转发确认(要签名)、改设置 | 不知道主密码(除非你输了) |
288
+ | **agent**(模型的 `bash`,同一用户,能读 `~/.ai-vault`) | 读到会话令牌文件(但插件开的会话没有 secret 用不了,一用就作废) | **伪造一次读取确认、给令牌加授权、改确认窗里的请求方、`list` 插件会话、拿到 Bitwarden 主密码** |
289
+ | **别的用户 / 离线拿到文件的人** | 读到密文 | 解密(scrypt + ChaCha20-Poly1305) |
290
+
291
+ ### 怎么做到的
292
+
293
+ - **确认窗不能被绕过。** `vault_get` 的确认要么是 CLI 自己开的 zenity 窗口,要么是宿主转发的答案。转发的答案必须带 `--approval`:用**宿主进程内存里的 secret** 对 `allow:<token>:<条目>:<y|n>` 做 HMAC。模型的 bash 能找到令牌文件,但没有 secret,签不出来;拿别的条目的签名重放、把 `n` 改成 `y`,都会对不上。
294
+ - **令牌文件不能改。** 每个会话文件带 HMAC(宿主会话用 host secret,手敲 CLI 的会话用库目录的 wrap key)。改了 `grants`、改了 `requester`、哪怕只改一个字节,CLI 都报 `session file was modified outside ai-vault` 并删掉文件。
295
+ - **`grant` 不再是免费的。** 给一条条目「N 分钟免确认」是一次长期授权,现在要主密码(和切模式同一级别)。
296
+ - **`never` 模式是明确放弃上面这些。** 密钥写在 `~/.ai-vault/agent.session.json`,读取不再有任何窗口。它的意义是把「可以让 AI 随便用」和「每次都要问我」分开;开了它,就等于信任 agent 的输出渠道,不只是 agent。
297
+ - **Bitwarden 会话密钥加密封存。** `bitwarden.unlock = never|time` 时,`bw` 的会话密钥用 ChaCha20-Poly1305 封在 `~/.ai-vault/bitwarden.session.json` 下,密钥是 `~/.ai-vault/.wrap`(0600)。单独拷走那个文件什么都打不开。`bw unlock --raw` 的会话密钥等价于**整个** Bitwarden 保险库的读权限,所以这个文件的敏感度 ≥ 库本身。
298
+ - **确认窗里的字不是模型写的。** 条目名、原因、用户名、URI 进窗口前都压成一行、去掉控制字符、截到 80–120 字符,模型没法在名字里塞换行伪造第二条「已授权」。
299
+ - **KDF。** 新库 scrypt `N=2^17`(128 MiB);文件头记着参数,旧库(`N=2^15`)照常打开,`ai-vault rekey` 升级。低于 `2^15` 的参数一律拒收(防降级)。
300
+ - **主密码**只经过弹窗或宿主输入框;`unlock` 派生的 key 只写进令牌文件(0600,优先 tmpfs)。`BW_*` 在所有子进程环境里剔除。
301
+ - **审计**:`~/.ai-vault/audit.log` 记录会话、条目、允许/拒绝/原因、以及 `unsigned-relay`、`bad-approval`、`modified-outside` 这类尝试,从不记值;1 MiB 轮转。
302
+ - **原子写 + flock**:临时文件(0600)→ fsync → rename → 目录 fsync;多进程读改写有文件锁。失效/被改/旧库的令牌文件每次调用都会被清掉。
303
+ - `bw_reveal` 默认关闭;擦洗只在值长度 ≥ 6 时生效,防不住网络外传和单向哈希——`bw_run` / `bw_inject` 的价值是值不进对话,不是防住被注入的 agent。
304
+ - `notes` 只在 `get`(授权之后)里出现,`list` 不输出它。
305
+
306
+ ### 已知边界
307
+
308
+ - `session` 模式下,模型的 bash **能**读到令牌文件,但拿到也没用:插件开的会话用宿主内存里的 secret 签名,bash 没有 secret,第一次用就会被判「文件被改」而作废(连 `list` 都做不了,还会把那个文件删掉)。只有**你在终端手敲** `ai-vault unlock` 开出来的会话(用 wrap key 签名)才能被同用户进程 `list`——那种会话本来就没有窗口可以绕,这是「同一用户」的固有暴露面。真正收紧要靠不同的用户或容器。
309
+ - 一个 `AI_VAULT_HOST=1` 但没带 secret 的调用方,会被当成普通用户对待:拿不到 secret、签不了转发。
310
+ - `bitwarden.import = always` + `bitwarden.unlock = never` 等于「Bitwarden 里任何一条被问到就自动进免费库」。README 不建议,但它能开。
311
+ - zenity 窗口的标题栏属于窗口管理器;全屏伪造窗口不在防护范围内。
245
312
 
246
313
  ## 开发
247
314
 
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ai-vault"
3
- version = "0.6.0"
3
+ version = "0.8.0"
4
4
  edition = "2021"
5
5
  description = "Machine-wide encrypted secret store shared by AI coding agents"
6
6
  license = "MIT"
@@ -16,6 +16,7 @@ chacha20poly1305 = "0.10"
16
16
  chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
17
17
  clap = { version = "4", features = ["derive", "env"] }
18
18
  getrandom = "0.2"
19
+ hmac = "0.12"
19
20
  scrypt = "0.11"
20
21
  serde = { version = "1", features = ["derive"] }
21
22
  serde_json = "1"
@@ -1,8 +1,11 @@
1
1
  //! The `bw` session key, persisted for `bitwarden.unlock = never | time`.
2
2
  //!
3
- //! `bw unlock` hands back a bearer key; keeping it on disk is what makes the
4
- //! Bitwarden side password-free, exactly like the vault's own `never` mode.
5
- //! It is never printed unless `bw-session get` is asked for it.
3
+ //! `bw unlock` hands back a bearer key for the *whole* Bitwarden vault, so the
4
+ //! file is sealed: ChaCha20-Poly1305 under a random 256-bit key in
5
+ //! `<dir>/.wrap` (0600, same directory and owner as the store). Copying the
6
+ //! session file away therefore yields nothing; it opens only together with
7
+ //! the directory that already holds the ai-vault store. It is never printed
8
+ //! unless `bw-session get` is asked for it.
6
9
 
7
10
  use std::fs;
8
11
  use std::os::unix::fs::PermissionsExt;
@@ -20,7 +23,73 @@ pub struct Stored {
20
23
  pub saved_at: i64,
21
24
  #[serde(default, skip_serializing_if = "Option::is_none", rename = "expiresAt")]
22
25
  pub expires_at: Option<i64>,
23
- pub key: String,
26
+ /// base64(iv(12) || ciphertext || tag(16)) of the key, under the wrap key.
27
+ pub sealed: String,
28
+ }
29
+
30
+ /// Load the wrap key, creating it on first use. It is a plain random file:
31
+ /// its protection is the directory (0700) and the owner, like the store.
32
+ fn wrap_key(paths: &Paths) -> Result<crypto::Key, String> {
33
+ let path = paths.wrap_key();
34
+ match fs::read(&path) {
35
+ Ok(bytes) if bytes.len() == 32 => {
36
+ let mut key = crypto::Key::new([0u8; 32]);
37
+ key.copy_from_slice(&bytes);
38
+ return Ok(key);
39
+ }
40
+ Ok(_) => {
41
+ // Wrong size: corrupt or foreign. Replace rather than fail; the
42
+ // only thing it protects is a session that can be re-unlocked.
43
+ let _ = fs::remove_file(&path);
44
+ }
45
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
46
+ Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
47
+ }
48
+ let fresh = crypto::random_bytes::<32>();
49
+ fs::create_dir_all(&paths.dir).map_err(|e| format!("cannot create {}: {e}", paths.dir.display()))?;
50
+ let _ = fs::set_permissions(&paths.dir, fs::Permissions::from_mode(0o700));
51
+ crypto::write_atomic(&path, &fresh)?;
52
+ let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
53
+ Ok(crypto::Key::new(fresh))
54
+ }
55
+
56
+ /// The wrap key as hex, for signing a non-host session file.
57
+ pub fn wrap_key_hex(paths: &Paths) -> Result<String, String> {
58
+ let key = wrap_key(paths)?;
59
+ Ok(key.iter().map(|b| format!("{b:02x}")).collect())
60
+ }
61
+
62
+ fn seal(wrap: &crypto::Key, plain: &str) -> Result<String, String> {
63
+ use chacha20poly1305::aead::{Aead, KeyInit};
64
+ use chacha20poly1305::{ChaCha20Poly1305, Nonce};
65
+ let iv = crypto::random_bytes::<12>();
66
+ let cipher = ChaCha20Poly1305::new_from_slice(wrap.as_ref()).map_err(|e| format!("wrap key: {e}"))?;
67
+ let body = cipher
68
+ .encrypt(Nonce::from_slice(&iv), plain.as_bytes())
69
+ .map_err(|_| "cannot seal session".to_string())?;
70
+ let mut blob = Vec::with_capacity(12 + body.len());
71
+ blob.extend_from_slice(&iv);
72
+ blob.extend_from_slice(&body);
73
+ use base64::Engine as _;
74
+ Ok(base64::engine::general_purpose::STANDARD.encode(blob))
75
+ }
76
+
77
+ fn unseal(wrap: &crypto::Key, sealed: &str) -> Result<String, String> {
78
+ use base64::Engine as _;
79
+ use chacha20poly1305::aead::{Aead, KeyInit};
80
+ use chacha20poly1305::{ChaCha20Poly1305, Nonce};
81
+ let blob = base64::engine::general_purpose::STANDARD
82
+ .decode(sealed.as_bytes())
83
+ .map_err(|_| "sealed session is not base64".to_string())?;
84
+ if blob.len() < 12 + 16 {
85
+ return Err("sealed session is truncated".into());
86
+ }
87
+ let (iv, body) = blob.split_at(12);
88
+ let cipher = ChaCha20Poly1305::new_from_slice(wrap.as_ref()).map_err(|e| format!("wrap key: {e}"))?;
89
+ cipher
90
+ .decrypt(Nonce::from_slice(iv), body)
91
+ .map_err(|_| "sealed session does not open under the wrap key".to_string())
92
+ .and_then(|plain| String::from_utf8(plain).map_err(|_| "sealed session is not UTF-8".to_string()))
24
93
  }
25
94
 
26
95
  impl Stored {
@@ -43,7 +112,8 @@ pub fn save(paths: &Paths, key: &str) -> Result<Option<i64>, String> {
43
112
  UnlockMode::Time => Some(now + policy.hours.clamp(1, 24 * 90) * 3_600_000),
44
113
  UnlockMode::Session => None,
45
114
  };
46
- let stored = Stored { saved_at: now, expires_at, key: key.to_string() };
115
+ let wrap = wrap_key(paths)?;
116
+ let stored = Stored { saved_at: now, expires_at, sealed: seal(&wrap, key)? };
47
117
  let bytes = serde_json::to_vec(&stored).map_err(|e| format!("cannot serialize session: {e}"))?;
48
118
  crypto::write_atomic(&paths.bw_session(), &bytes)?;
49
119
  let _ = fs::set_permissions(paths.bw_session(), fs::Permissions::from_mode(0o600));
@@ -71,6 +141,17 @@ pub fn load(paths: &Paths) -> Result<Option<Stored>, String> {
71
141
  Ok(Some(stored))
72
142
  }
73
143
 
144
+ /// The session key itself, or an error naming why it cannot be opened.
145
+ pub fn key(paths: &Paths) -> Result<Option<String>, String> {
146
+ match load(paths)? {
147
+ None => Ok(None),
148
+ Some(stored) => {
149
+ let wrap = wrap_key(paths)?;
150
+ unseal(&wrap, &stored.sealed).map(Some)
151
+ }
152
+ }
153
+ }
154
+
74
155
  pub fn clear(paths: &Paths) -> bool {
75
156
  fs::remove_file(paths.bw_session()).is_ok()
76
157
  }
@@ -123,9 +123,14 @@ enum Cmd {
123
123
  /// Why the secret is needed (shown in the confirm window)
124
124
  #[arg(long)]
125
125
  reason: Option<String>,
126
- /// Read the approve/deny answer from stdin (host UI already asked)
126
+ /// Read the approve/deny answer from stdin (host UI already asked).
127
+ /// Requires AI_VAULT_HOST=1 and a matching --approval.
127
128
  #[arg(long)]
128
129
  answer_stdin: bool,
130
+ /// HMAC-SHA256(hex) of "allow:<token>:<entry>:y|n" under the host
131
+ /// secret, proving a host that holds the secret relayed the answer.
132
+ #[arg(long, value_name = "HEX")]
133
+ approval: Option<String>,
129
134
  },
130
135
  /// Create or update an entry; the password is typed in a dialog
131
136
  Add {
@@ -193,6 +198,11 @@ enum Cmd {
193
198
  #[arg(long, env = "AI_VAULT_TOKEN")]
194
199
  token: Option<String>,
195
200
  },
201
+ /// Re-encrypt the store under the current default KDF (asks the master password)
202
+ Rekey {
203
+ #[arg(long)]
204
+ password_stdin: bool,
205
+ },
196
206
  /// Diagnose paths, session directory and desktop availability
197
207
  Doctor,
198
208
  }
@@ -237,6 +247,11 @@ pub fn run() -> i32 {
237
247
  };
238
248
  let paths = Paths::resolve(cli.dir.clone());
239
249
  migrate_legacy(&paths);
250
+ // Dead token files (expired, unsigned, from an older store) carry keys
251
+ // that open nothing; drop them on sight rather than after a week.
252
+ if paths.sessions().is_dir() {
253
+ session::sweep(&paths);
254
+ }
240
255
  let json = cli.json;
241
256
  match dispatch(cli.cmd, &paths, json) {
242
257
  Ok(()) => 0,
@@ -295,6 +310,7 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
295
310
  out.text(paths.store().display().to_string());
296
311
  Ok(())
297
312
  }
313
+ Cmd::Rekey { password_stdin } => rekey(paths, &out, password_stdin),
298
314
  Cmd::Doctor => doctor(paths, &out),
299
315
  Cmd::Init { password_stdin, requester, idle_min } => {
300
316
  init(paths, &out, password_stdin, &requester, idle_min)
@@ -312,8 +328,8 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
312
328
  Cmd::Status { token } => status(paths, &out, token),
313
329
  Cmd::Lock { token, all } => lock(paths, &out, token, all),
314
330
  Cmd::List { token } => list(paths, &out, token),
315
- Cmd::Get { name, token, reason, answer_stdin } => {
316
- get(paths, &out, token, &name, reason.as_deref(), answer_stdin)
331
+ Cmd::Get { name, token, reason, answer_stdin, approval } => {
332
+ get(paths, &out, token, &name, reason.as_deref(), answer_stdin, approval)
317
333
  }
318
334
  Cmd::Add { name, username, uri, notes, password_stdin, yes, token } => {
319
335
  add(paths, &out, token, AddRequest { name, username, uri, notes, password_stdin, yes })
@@ -405,6 +421,21 @@ fn read_stdin_text() -> Result<String, Fault> {
405
421
  }
406
422
 
407
423
  /// A yes/no answer from stdin, used when the host UI already asked the user.
424
+ /// The answer a host relays is bound to this token, this entry and this
425
+ /// yes/no, under the host secret: a replay against another entry, or a
426
+ /// flipped answer, fails.
427
+ fn approval_ok(secret: &str, token: &str, entry: &str, answer: bool, hex_mac: &str) -> bool {
428
+ use hmac::{Hmac, Mac};
429
+ let message = format!("allow:{token}:{}:{}", entry.to_lowercase(), if answer { "y" } else { "n" });
430
+ let Ok(mut hasher) = <Hmac<sha2::Sha256> as Mac>::new_from_slice(secret.as_bytes()) else {
431
+ return false;
432
+ };
433
+ hasher.update(message.as_bytes());
434
+ let expected: String = hasher.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
435
+ expected.len() == hex_mac.len()
436
+ && expected.bytes().zip(hex_mac.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0
437
+ }
438
+
408
439
  fn read_approval() -> Result<bool, Fault> {
409
440
  let answer = read_line()?.trim().to_lowercase();
410
441
  Ok(matches!(answer.as_str(), "y" | "yes" | "allow" | "允许" | "1" | "true"))
@@ -444,6 +475,31 @@ fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>,
444
475
  })
445
476
  }
446
477
 
478
+ /// The secret the host process (pi/omp extension) holds and passes to each
479
+ /// CLI call through the environment. A bare `ai-vault` typed by a human has
480
+ /// none, which is fine: that caller never needs to relay an approval.
481
+ fn host_secret() -> Option<String> {
482
+ std::env::var("AI_VAULT_HOST_SECRET").ok().filter(|s| !s.is_empty())
483
+ }
484
+
485
+ /// What session files are signed with: the host's memory-only secret when
486
+ /// there is one, else the store's wrap key (a human at a terminal).
487
+ fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
488
+ if let Some(secret) = host_secret() {
489
+ return Ok(Some(secret));
490
+ }
491
+ bwsession::wrap_key_hex(paths).map(Some)
492
+ }
493
+
494
+ /// The host integration (the extension) is recognised by the secret it
495
+ /// presents: `AI_VAULT_HOST=1` alone only says "I would like to be a host"
496
+ /// and is treated like a human caller until it has a secret to sign with.
497
+ /// This keeps a half-configured host from getting a session it can neither
498
+ /// verify nor relay for.
499
+ fn is_host() -> bool {
500
+ std::env::var_os("AI_VAULT_HOST").is_some_and(|v| v == "1") && host_secret().is_some()
501
+ }
502
+
447
503
  /// The auto session is the `never` mode token: no deadline, no password, and
448
504
  /// it belongs to the machine rather than to one agent.
449
505
  fn auto_session(paths: &Paths) -> Option<Session> {
@@ -459,7 +515,7 @@ fn auto_session(paths: &Paths) -> Option<Session> {
459
515
  /// An explicit token, else the machine-wide auto session.
460
516
  fn load_session(paths: &Paths, token: Option<&str>) -> Result<Session, Fault> {
461
517
  if let Some(token) = token.filter(|t| !t.is_empty()) {
462
- return session::load(paths, token).map_err(Fault::Auth);
518
+ return session::load(paths, token, signing_key(paths)?.as_deref()).map_err(Fault::Auth);
463
519
  }
464
520
  auto_session(paths).ok_or_else(|| {
465
521
  Fault::Auth("vault is locked (no session token) — unlock first".into())
@@ -473,7 +529,16 @@ fn persist(paths: &Paths, session: &Session) {
473
529
  .ok()
474
530
  .flatten()
475
531
  .is_some_and(|saved| saved.token == session.token);
476
- let _ = if auto { session::save_auto(paths, session) } else { session.save(paths) };
532
+ let _ = if auto {
533
+ session::save_auto(paths, session)
534
+ } else {
535
+ // Best-effort like the rest of this helper; a failed sign means the
536
+ // next call simply asks to unlock again.
537
+ match signing_key(paths) {
538
+ Ok(key) => session.save(paths, key.as_deref()),
539
+ Err(e) => Err(e),
540
+ }
541
+ };
477
542
  }
478
543
 
479
544
  fn touch(paths: &Paths, session: &mut Session) {
@@ -505,6 +570,42 @@ where
505
570
 
506
571
  // ---------------------------------------------------------------- commands
507
572
 
573
+ /// Bring an older store up to the current KDF cost. Re-derives the key from
574
+ /// the password under the new parameters and re-seals; a `never`-mode
575
+ /// machine session, which holds the old key, is re-minted.
576
+ fn rekey(paths: &Paths, out: &Out, password_stdin: bool) -> Outcome {
577
+ let store = open_store(paths)?;
578
+ let password = if password_stdin {
579
+ read_password()?
580
+ } else {
581
+ ask_password("ai-vault · 升级密钥参数", "主密码")?
582
+ };
583
+ let (items, _old_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
584
+ crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
585
+ crypto::OpenError::Broken(message) => Fault::Error(message),
586
+ })?;
587
+ let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| Fault::Error("vault salt is corrupt".into()))?;
588
+ let kdf = Kdf::default();
589
+ let new_key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
590
+ let sealed = crypto::seal(&salt, kdf, &new_key, &items)?;
591
+ {
592
+ let _guard = StoreLock::acquire(paths)?;
593
+ let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
594
+ crypto::write_atomic(&paths.store(), &bytes)?;
595
+ }
596
+ // Other live sessions hold the old key; they cannot open the new file and
597
+ // will be told to unlock again. The machine session is simply re-minted.
598
+ let _ = session::delete_auto(paths);
599
+ if config::load(paths).unlock.mode == UnlockMode::Never {
600
+ let auto = Session::new("rekey", 0, None, &sealed, &new_key);
601
+ session::save_auto(paths, &auto)?;
602
+ }
603
+ audit::append(&paths.audit(), "cli", "rekey", None, Some(&format!("N={}", kdf.n)));
604
+ let value = json!({ "ok": true, "kdf": { "N": kdf.n, "r": kdf.r, "p": kdf.p }, "was": { "N": store.kdf().n, "r": store.kdf().r, "p": store.kdf().p } });
605
+ out.value(value, || format!("rekeyed: scrypt N {} -> {}", store.kdf().n, kdf.n));
606
+ Ok(())
607
+ }
608
+
508
609
  fn doctor(paths: &Paths, out: &Out) -> Outcome {
509
610
  session::ensure_session_dir(paths)?;
510
611
  let value = json!({
@@ -518,6 +619,7 @@ fn doctor(paths: &Paths, out: &Out) -> Outcome {
518
619
  "zenity": which("zenity"),
519
620
  "mode": config::load(paths).unlock.mode.as_str(),
520
621
  "auto": paths.auto_session().exists(),
622
+ "kdf": crypto::read_store(&paths.store()).ok().flatten().map(|s| s.kdf().n),
521
623
  });
522
624
  out.value(value.clone(), || {
523
625
  let mut lines = Vec::new();
@@ -573,17 +675,19 @@ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_mi
573
675
  }
574
676
  session::ensure_session_dir(paths)?;
575
677
  let (idle, deadline, policy) = policy(paths, idle_min);
678
+ let secret = signing_key(paths)?;
576
679
  let session = Session::new(requester, idle, deadline, &sealed, &key);
577
680
  if policy.mode == UnlockMode::Never {
578
681
  session::save_auto(paths, &session)?;
579
682
  } else {
580
- session.save(paths)?;
683
+ session.save(paths, secret.as_deref())?;
581
684
  }
582
685
  audit::append(&paths.audit(), requester, "init", None, None);
583
686
  let value = json!({
584
687
  "ok": true,
585
688
  "path": paths.store(),
586
689
  "token": session.token,
690
+ "hostSecret": if policy.mode == UnlockMode::Never || !is_host() { None } else { host_secret() },
587
691
  "expiresAt": session.expiry(),
588
692
  "items": 0,
589
693
  "mode": policy.mode.as_str(),
@@ -610,16 +714,22 @@ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_
610
714
  session::ensure_session_dir(paths)?;
611
715
  session::sweep(paths);
612
716
  let (idle, deadline, policy) = policy(paths, idle_min);
717
+ // A host that did not pass a secret gets a fresh one to keep for this
718
+ // session: it is the only thing that can sign later edits to the file.
719
+ // The host brings its own secret (so the same process can sign later
720
+ // calls); everyone else is signed with the wrap key.
721
+ let secret = signing_key(paths)?;
613
722
  let session = Session::new(requester, idle, deadline, &store, &key);
614
723
  if policy.mode == UnlockMode::Never {
615
724
  session::save_auto(paths, &session)?;
616
725
  } else {
617
- session.save(paths)?;
726
+ session.save(paths, secret.as_deref())?;
618
727
  }
619
728
  audit::append(&paths.audit(), requester, "unlock", None, Some(policy.mode.as_str()));
620
729
  let value = json!({
621
730
  "ok": true,
622
731
  "token": session.token,
732
+ "hostSecret": if policy.mode == UnlockMode::Never || !is_host() { None } else { host_secret() },
623
733
  "expiresAt": session.expiry(),
624
734
  "items": items.len(),
625
735
  "requester": requester,
@@ -808,9 +918,10 @@ fn bw_session(paths: &Paths, out: &Out, action: &str) -> Outcome {
808
918
  "" | "get" => {
809
919
  let stored = bwsession::load(paths)?
810
920
  .ok_or_else(|| Fault::Auth("no persisted Bitwarden session — unlock Bitwarden first".into()))?;
921
+ let key = bwsession::key(paths)?.ok_or_else(|| Fault::Auth("no persisted Bitwarden session".into()))?;
811
922
  out.value(
812
- json!({ "ok": true, "key": stored.key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
813
- || stored.key.clone(),
923
+ json!({ "ok": true, "key": key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
924
+ || key,
814
925
  );
815
926
  Ok(())
816
927
  }
@@ -945,6 +1056,7 @@ fn get(
945
1056
  name: &str,
946
1057
  reason: Option<&str>,
947
1058
  answer_stdin: bool,
1059
+ approval: Option<String>,
948
1060
  ) -> Outcome {
949
1061
  let mut session = load_session(paths, token.as_deref())?;
950
1062
  let store = open_store(paths)?;
@@ -963,14 +1075,32 @@ fn get(
963
1075
  } else if session.grant(&item.name, now).is_some() {
964
1076
  "existing-grant"
965
1077
  } else {
1078
+ // The window is what the user approves: no caller-supplied text may
1079
+ // break out of its own line here.
966
1080
  let message = format!(
967
1081
  "条目: {}\n请求方: {}\n原因: {}\n\n允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
968
- item.name,
969
- session.requester,
970
- reason.unwrap_or("(未说明)")
1082
+ dialog::for_dialog(&item.name, 80),
1083
+ dialog::for_dialog(&session.requester, 40),
1084
+ dialog::for_dialog(reason.unwrap_or("(未说明)"), 120)
971
1085
  );
972
1086
  let approved = if answer_stdin {
973
- read_approval()?
1087
+ // Relaying an answer is a host privilege: it must be signed with the
1088
+ // host secret, so the model's own bash cannot answer "y" for the user.
1089
+ let Some(secret) = host_secret().filter(|_| is_host()) else {
1090
+ audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), Some("unsigned-relay"));
1091
+ return Err(Fault::Usage(
1092
+ "--answer-stdin is only for a host that holds AI_VAULT_HOST_SECRET and signs the answer with --approval".into(),
1093
+ ));
1094
+ };
1095
+ let answer = read_approval()?;
1096
+ let Some(approval) = approval else {
1097
+ return Err(Fault::Usage("--answer-stdin needs --approval <hmac of the answer>".into()));
1098
+ };
1099
+ if !approval_ok(&secret, &session.token, &item.name, answer, &approval) {
1100
+ audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), Some("bad-approval"));
1101
+ return Err(Fault::Denied(format!("approval signature mismatch for \"{}\"", item.name)));
1102
+ }
1103
+ answer
974
1104
  } else {
975
1105
  match dialog::confirm("ai-vault · 读取本地密码", &message) {
976
1106
  Answer::Value(ok) => ok,
@@ -1031,18 +1161,19 @@ fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outc
1031
1161
  if !req.yes {
1032
1162
  let mut meta = Vec::new();
1033
1163
  if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
1034
- meta.push(format!("用户名: {user}"));
1164
+ meta.push(format!("用户名: {}", dialog::for_dialog(user, 60)));
1035
1165
  }
1036
1166
  if let Some(uri) = req.uri.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
1037
- meta.push(format!("URI: {uri}"));
1167
+ meta.push(format!("URI: {}", dialog::for_dialog(uri, 120)));
1038
1168
  }
1039
1169
  if let Some(notes) = req.notes.as_deref().map(str::trim).filter(|n| !n.is_empty()) {
1040
- meta.push(format!("备注: {notes}"));
1170
+ meta.push(format!("备注: {}", dialog::for_dialog(notes, 120)));
1041
1171
  }
1172
+ let shown = dialog::for_dialog(&name, 80);
1042
1173
  let action = if existing.is_some() {
1043
- format!("更新已有条目「{name}」。")
1174
+ format!("更新已有条目「{shown}」。")
1044
1175
  } else {
1045
- format!("新建条目「{name}」。")
1176
+ format!("新建条目「{shown}」。")
1046
1177
  };
1047
1178
  let message = format!(
1048
1179
  "{action}{}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。",
@@ -1140,7 +1271,7 @@ fn remove(paths: &Paths, out: &Out, token: Option<String>, name: &str, yes: bool
1140
1271
  return Err(Fault::Error(format!("no such entry: \"{name}\"")));
1141
1272
  }
1142
1273
  if !yes {
1143
- match dialog::confirm("ai-vault · 删除条目", &format!("删除「{name}」?删除后无法恢复。")) {
1274
+ match dialog::confirm("ai-vault · 删除条目", &format!("删除「{}」?删除后无法恢复。", dialog::for_dialog(name, 80))) {
1144
1275
  Answer::Value(true) => {}
1145
1276
  Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
1146
1277
  Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
@@ -1159,9 +1290,28 @@ fn remove(paths: &Paths, out: &Out, token: Option<String>, name: &str, yes: bool
1159
1290
  Ok(())
1160
1291
  }
1161
1292
 
1293
+ /// A grant is "no window for N minutes": it is a standing approval, so it
1294
+ /// costs the master password — the same as changing the unlock mode. The
1295
+ /// interactive `/vault grant` asks through the window; a non-host caller
1296
+ /// without the password cannot mint one.
1162
1297
  fn grant(paths: &Paths, out: &Out, token: Option<String>, name: &str, minutes: Option<i64>) -> Outcome {
1163
1298
  let mut session = load_session(paths, token.as_deref())?;
1164
1299
  let store = open_store(paths)?;
1300
+ {
1301
+ // Only the host may use --password-stdin here (it just asked the user);
1302
+ // anyone else gets the window.
1303
+ let password = if is_host() {
1304
+ read_password()?
1305
+ } else {
1306
+ ask_password("ai-vault · 授权读取", "主密码(给一条条目免确认读取)")?
1307
+ };
1308
+ if let Err(e) = crypto::open_with_passphrase(&store, &password) {
1309
+ return Err(match e {
1310
+ crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
1311
+ crypto::OpenError::Broken(message) => Fault::Error(message),
1312
+ });
1313
+ }
1314
+ }
1165
1315
  let items = items_with(&session, &store)?;
1166
1316
  let item = store::find(&items, name).ok_or_else(|| Fault::Error(format!("no such entry: \"{name}\"")))?;
1167
1317
  let minutes = minutes.unwrap_or(GRANT_MS_DEFAULT / 60_000).clamp(1, GRANT_MS_MAX / 60_000);
@@ -1226,7 +1376,13 @@ fn import_file(paths: &Paths, out: &Out, token: Option<String>, file: &PathBuf,
1226
1376
  let shown = drafts
1227
1377
  .iter()
1228
1378
  .take(15)
1229
- .map(|d| format!("• {}{}", d.name, d.username.as_ref().map(|u| format!(" user:{u}")).unwrap_or_default()))
1379
+ .map(|d| {
1380
+ format!(
1381
+ "• {}{}",
1382
+ dialog::for_dialog(&d.name, 80),
1383
+ d.username.as_ref().map(|u| format!(" user:{}", dialog::for_dialog(u, 40))).unwrap_or_default()
1384
+ )
1385
+ })
1230
1386
  .collect::<Vec<_>>()
1231
1387
  .join("\n");
1232
1388
  let more = if drafts.len() > 15 { format!("\n… 还有 {} 条", drafts.len() - 15) } else { String::new() };