@xiaolikt/ai-vault 0.4.1 → 0.5.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.
@@ -0,0 +1,77 @@
1
+ //! Machine-wide unlock policy: how often the vault asks for the master
2
+ //! password. Switching the mode always re-verifies the master password.
3
+
4
+ use serde::{Deserialize, Serialize};
5
+ use std::fs;
6
+
7
+ use crate::crypto;
8
+ use crate::paths::Paths;
9
+
10
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11
+ #[serde(rename_all = "kebab-case")]
12
+ pub enum UnlockMode {
13
+ /// Never ask again: the key lives in the store directory, readable by this
14
+ /// user, so agents can read secrets without any window.
15
+ Never,
16
+ /// Ask again after `hours`, counted from the unlock (not from the last use).
17
+ Time,
18
+ /// Ask once per agent session; the token dies when the session ends.
19
+ Session,
20
+ }
21
+
22
+ impl UnlockMode {
23
+ pub fn parse(text: &str) -> Option<UnlockMode> {
24
+ match text.trim().to_lowercase().as_str() {
25
+ "never" | "no-password" | "none" | "off" => Some(UnlockMode::Never),
26
+ "time" | "hours" => Some(UnlockMode::Time),
27
+ "session" | "on" => Some(UnlockMode::Session),
28
+ _ => None,
29
+ }
30
+ }
31
+
32
+ pub fn as_str(self) -> &'static str {
33
+ match self {
34
+ UnlockMode::Never => "never",
35
+ UnlockMode::Time => "time",
36
+ UnlockMode::Session => "session",
37
+ }
38
+ }
39
+ }
40
+
41
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
42
+ pub struct UnlockPolicy {
43
+ pub mode: UnlockMode,
44
+ /// `Time` mode only: hours between password prompts.
45
+ #[serde(default = "default_hours")]
46
+ pub hours: i64,
47
+ }
48
+
49
+ fn default_hours() -> i64 {
50
+ 8
51
+ }
52
+
53
+ impl Default for UnlockPolicy {
54
+ fn default() -> Self {
55
+ UnlockPolicy { mode: UnlockMode::Session, hours: default_hours() }
56
+ }
57
+ }
58
+
59
+ #[derive(Debug, Clone, Serialize, Deserialize, Default)]
60
+ pub struct Config {
61
+ #[serde(default)]
62
+ pub unlock: UnlockPolicy,
63
+ }
64
+
65
+ /// A missing or unreadable config means the default policy: ask once per
66
+ /// session. A broken file must not lock anyone out of their vault.
67
+ pub fn load(paths: &Paths) -> Config {
68
+ match fs::read_to_string(paths.config()) {
69
+ Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
70
+ Err(_) => Config::default(),
71
+ }
72
+ }
73
+
74
+ pub fn save(paths: &Paths, config: &Config) -> Result<(), String> {
75
+ let bytes = serde_json::to_vec_pretty(config).map_err(|e| format!("cannot serialize config: {e}"))?;
76
+ crypto::write_atomic(&paths.config(), &bytes)
77
+ }
@@ -8,6 +8,7 @@
8
8
 
9
9
  mod audit;
10
10
  mod cli;
11
+ mod config;
11
12
  mod crypto;
12
13
  mod dialog;
13
14
  mod import;
@@ -32,6 +32,16 @@ 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
+
35
45
  /// Shared advisory lock for read-modify-write of the store file.
36
46
  pub fn store_lock(&self) -> PathBuf {
37
47
  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
- now.saturating_sub(self.last_active) >= self.idle_ms
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
- pub fn expires_at(&self) -> i64 {
76
- self.last_active + self.idle_ms
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.1",
4
- "description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable) plus a thin pi/omp extension that calls it.",
3
+ "version": "0.5.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.4.1"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.5.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,62 @@
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 搜;命中后先给你看这一条并问是否读取,读了再问「导入 ai-vault(以后免 Bitwarden)还是只用这一次」。所以 **只有你同意导入的密码才会进 ai-vault**。
55
+
56
+ ## 隔离
57
+
58
+ 每个会话、每个子代理各自 `ai-vault unlock`,拿自己的令牌和读授权;父会话的解锁子代理继承不到。空闲 10 分钟自动失效,`/new`、`/fork`、退出会清掉本绑定的令牌。
59
+
60
+ 完整说明(CLI 参数、退出码契约、Bitwarden 擦洗、审计、安全模型)见仓库 README:https://github.com/xiaolikt/ai-vault
61
+
62
+ MIT
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "pi-ai-vault",
3
+ "version": "0.5.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.5.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
+ }
@@ -779,6 +779,38 @@ export async function pullBitwardenLogins(
779
779
  return filterLogins(bitwardenLogins(raw), search);
780
780
  }
781
781
 
782
+ export type BitwardenLoginHit = { id: string; name: string; username: string; password: string; uris: string[] };
783
+
784
+ /**
785
+ * Look one login up by name/URI and return its password, with no window of its
786
+ * own: the caller shows the user what was found and asks whether to read it.
787
+ * `undefined` means "no such item"; an ambiguous reference throws with the
788
+ * candidates so the model can pick one.
789
+ */
790
+ export async function lookupBitwardenLogin(
791
+ st: BwState,
792
+ ctx: ExtensionContext | undefined,
793
+ ref: string,
794
+ signal?: AbortSignal,
795
+ ): Promise<BitwardenLoginHit | undefined> {
796
+ const session = await ensureUnlocked(st, ctx, signal);
797
+ let item: LiteItem;
798
+ try {
799
+ item = await resolveItem(st, session, ref, signal);
800
+ } catch (e) {
801
+ if (e instanceof Error && /^No Bitwarden item matches/.test(e.message)) return undefined;
802
+ throw e;
803
+ }
804
+ const secret = await secretOf(session, item, "password", signal);
805
+ return {
806
+ id: item.id ?? "",
807
+ name: item.name || "unnamed",
808
+ username: item.username,
809
+ password: secret.value,
810
+ uris: item.uri ? [item.uri] : [],
811
+ };
812
+ }
813
+
782
814
  function normalizeEnvName(raw: string): string {
783
815
  const name = raw.trim().toUpperCase();
784
816
  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
- /** `AI_VAULT_BIN`, then PATH, then the usual install spots. */
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
- for (const dir of (process.env.PATH ?? "").split(delimiter)) {
58
- if (!dir) continue;
59
- const candidate = join(dir, "ai-vault");
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")]) {