@xiaolikt/ai-vault 0.0.0-stage → 0.4.1
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 +784 -0
- package/Cargo.toml +8 -0
- package/LICENSE +21 -0
- package/README.md +188 -2
- package/bin/ai-vault.cjs +71 -0
- package/crates/ai-vault/Cargo.toml +26 -0
- package/crates/ai-vault/src/audit.rs +77 -0
- package/crates/ai-vault/src/cli.rs +942 -0
- package/crates/ai-vault/src/crypto.rs +265 -0
- package/crates/ai-vault/src/dialog.rs +222 -0
- package/crates/ai-vault/src/import.rs +175 -0
- package/crates/ai-vault/src/main.rs +21 -0
- package/crates/ai-vault/src/paths.rs +58 -0
- package/crates/ai-vault/src/session.rs +230 -0
- package/crates/ai-vault/src/store.rs +219 -0
- package/install.sh +21 -0
- package/package.json +76 -5
- package/src/bitwarden.ts +1450 -0
- package/src/cli.ts +155 -0
- package/src/host.ts +76 -0
- package/src/import-map.ts +91 -0
- package/src/index.ts +772 -0
- package/src/prompt.ts +195 -0
- package/src/scrub.ts +157 -0
- package/test/cli.sh +120 -0
- package/test/npm.sh +70 -0
- package/test/smoke.sh +77 -0
- package/tests/bitwarden-tools.test.mjs +330 -0
- package/tests/helpers.mjs +129 -0
- package/tests/import-map.test.mjs +74 -0
- package/tests/mocks/bin/bw +41 -0
- package/tests/mocks/bin/wl-copy +15 -0
- package/tests/mocks/bin/wl-paste +9 -0
- package/tests/mocks/bin/zenity +43 -0
- package/tests/prompt.test.mjs +200 -0
- package/tests/register.test.mjs +48 -0
- package/tests/scrub.test.mjs +98 -0
- package/tests/vault-cli.test.mjs +131 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
//! Where the store, its sessions and its audit log live.
|
|
2
|
+
|
|
3
|
+
use std::env;
|
|
4
|
+
use std::path::{Path, PathBuf};
|
|
5
|
+
|
|
6
|
+
/// Idle time after which a session token stops working.
|
|
7
|
+
pub const IDLE_MS_DEFAULT: i64 = 10 * 60 * 1000;
|
|
8
|
+
/// Default lifetime of a read grant.
|
|
9
|
+
pub const GRANT_MS_DEFAULT: i64 = 5 * 60 * 1000;
|
|
10
|
+
/// Longest grant a caller may ask for.
|
|
11
|
+
pub const GRANT_MS_MAX: i64 = 60 * 60 * 1000;
|
|
12
|
+
|
|
13
|
+
#[derive(Clone, Debug)]
|
|
14
|
+
pub struct Paths {
|
|
15
|
+
pub dir: PathBuf,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
impl Paths {
|
|
19
|
+
/// `--dir`, else `$AI_VAULT_DIR`, else `~/.ai-vault`.
|
|
20
|
+
pub fn resolve(dir: Option<PathBuf>) -> Self {
|
|
21
|
+
let dir = dir
|
|
22
|
+
.or_else(|| env::var_os("AI_VAULT_DIR").map(PathBuf::from))
|
|
23
|
+
.unwrap_or_else(|| home().join(".ai-vault"));
|
|
24
|
+
Paths { dir }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
pub fn store(&self) -> PathBuf {
|
|
28
|
+
self.dir.join("store.json")
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
pub fn audit(&self) -> PathBuf {
|
|
32
|
+
self.dir.join("audit.log")
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Shared advisory lock for read-modify-write of the store file.
|
|
36
|
+
pub fn store_lock(&self) -> PathBuf {
|
|
37
|
+
self.dir.join("store.lock")
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Session tokens hold key material, so they prefer tmpfs when there is one:
|
|
41
|
+
/// they vanish at logout instead of lying on disk.
|
|
42
|
+
pub fn sessions(&self) -> PathBuf {
|
|
43
|
+
match env::var_os("XDG_RUNTIME_DIR") {
|
|
44
|
+
Some(runtime) if !runtime.is_empty() && self.dir == Paths::resolve(None).dir => {
|
|
45
|
+
PathBuf::from(runtime).join("ai-vault").join("sessions")
|
|
46
|
+
}
|
|
47
|
+
_ => self.dir.join("sessions"),
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
pub fn session_file(&self, token: &str) -> PathBuf {
|
|
52
|
+
self.sessions().join(format!("{token}.json"))
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
pub fn home() -> PathBuf {
|
|
57
|
+
env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| Path::new(".").to_path_buf())
|
|
58
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
//! Session tokens: how a caller keeps the store open without ever holding the
|
|
2
|
+
//! master password.
|
|
3
|
+
//!
|
|
4
|
+
//! `ai-vault unlock` derives the key, writes a token file (0600, under tmpfs
|
|
5
|
+
//! when there is one) and prints the token. Every later call presents the
|
|
6
|
+
//! token; the key is read from that file, never from the command line. A token
|
|
7
|
+
//! dies on `lock`, after `idleMs` without use, or when the store file changes
|
|
8
|
+
//! underneath it.
|
|
9
|
+
|
|
10
|
+
use std::collections::BTreeMap;
|
|
11
|
+
use std::fs;
|
|
12
|
+
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
|
13
|
+
|
|
14
|
+
use base64::engine::general_purpose::STANDARD as B64;
|
|
15
|
+
use base64::Engine as _;
|
|
16
|
+
use serde::{Deserialize, Serialize};
|
|
17
|
+
use zeroize::Zeroizing;
|
|
18
|
+
|
|
19
|
+
use crate::crypto::{self, Kdf};
|
|
20
|
+
use crate::paths::Paths;
|
|
21
|
+
|
|
22
|
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
23
|
+
pub struct Session {
|
|
24
|
+
pub token: String,
|
|
25
|
+
#[serde(default)]
|
|
26
|
+
pub requester: String,
|
|
27
|
+
#[serde(rename = "createdAt")]
|
|
28
|
+
pub created_at: i64,
|
|
29
|
+
#[serde(rename = "lastActive")]
|
|
30
|
+
pub last_active: i64,
|
|
31
|
+
#[serde(rename = "idleMs")]
|
|
32
|
+
pub idle_ms: i64,
|
|
33
|
+
#[serde(rename = "storeId")]
|
|
34
|
+
pub store_id: String,
|
|
35
|
+
pub salt: String,
|
|
36
|
+
#[serde(default)]
|
|
37
|
+
pub kdf: Option<Kdf>,
|
|
38
|
+
pub key: String,
|
|
39
|
+
/// entry name (lowercase) -> grant expiry epoch ms
|
|
40
|
+
#[serde(default)]
|
|
41
|
+
pub grants: BTreeMap<String, i64>,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
impl Session {
|
|
45
|
+
pub fn new(requester: &str, idle_ms: i64, store: &crypto::StoreFile, key: &[u8; 32]) -> Self {
|
|
46
|
+
let now = now_ms();
|
|
47
|
+
Session {
|
|
48
|
+
token: crate::store::random_id() + &crate::store::random_id(),
|
|
49
|
+
requester: requester.to_string(),
|
|
50
|
+
created_at: now,
|
|
51
|
+
last_active: now,
|
|
52
|
+
idle_ms,
|
|
53
|
+
store_id: crypto::store_id(store),
|
|
54
|
+
salt: store.salt.clone(),
|
|
55
|
+
kdf: Some(store.kdf()),
|
|
56
|
+
key: B64.encode(key),
|
|
57
|
+
grants: BTreeMap::new(),
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
pub fn key(&self) -> Option<Zeroizing<[u8; 32]>> {
|
|
62
|
+
let raw = B64.decode(self.key.as_bytes()).ok()?;
|
|
63
|
+
if raw.len() != 32 {
|
|
64
|
+
return None;
|
|
65
|
+
}
|
|
66
|
+
let mut key = Zeroizing::new([0u8; 32]);
|
|
67
|
+
key.copy_from_slice(&raw);
|
|
68
|
+
Some(key)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
pub fn expired(&self, now: i64) -> bool {
|
|
72
|
+
now.saturating_sub(self.last_active) >= self.idle_ms
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
pub fn expires_at(&self) -> i64 {
|
|
76
|
+
self.last_active + self.idle_ms
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// Drop grants that ran out. Returns true when anything was removed.
|
|
80
|
+
pub fn prune_grants(&mut self, now: i64) -> bool {
|
|
81
|
+
let before = self.grants.len();
|
|
82
|
+
self.grants.retain(|_, until| *until > now);
|
|
83
|
+
before != self.grants.len()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
pub fn grant(&self, name: &str, now: i64) -> Option<i64> {
|
|
87
|
+
self.grants
|
|
88
|
+
.get(&name.to_lowercase())
|
|
89
|
+
.copied()
|
|
90
|
+
.filter(|until| *until > now)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
pub fn save(&self, paths: &Paths) -> Result<(), String> {
|
|
94
|
+
let dir = paths.sessions();
|
|
95
|
+
fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
|
96
|
+
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
|
|
97
|
+
let text = serde_json::to_vec(self).map_err(|e| format!("cannot serialize session: {e}"))?;
|
|
98
|
+
crypto::write_atomic(&paths.session_file(&self.token), &text)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/// Load a token for the given store. Missing, expired, or stale tokens are
|
|
103
|
+
/// removed and reported as locked so the caller unlocks again.
|
|
104
|
+
pub fn load(paths: &Paths, token: &str) -> Result<Session, String> {
|
|
105
|
+
let path = paths.session_file(token);
|
|
106
|
+
let text = match fs::read_to_string(&path) {
|
|
107
|
+
Ok(text) => text,
|
|
108
|
+
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
|
109
|
+
return Err("vault is locked (no unlock in this session)".into())
|
|
110
|
+
}
|
|
111
|
+
Err(e) => return Err(format!("cannot read session {}: {e}", path.display())),
|
|
112
|
+
};
|
|
113
|
+
let session: Session = serde_json::from_str(&text)
|
|
114
|
+
.map_err(|_| "session token is corrupt — unlock again".to_string())?;
|
|
115
|
+
let now = now_ms();
|
|
116
|
+
if session.expired(now) {
|
|
117
|
+
let _ = fs::remove_file(&path);
|
|
118
|
+
return Err("vault locked itself after 10 minutes idle — unlock again".into());
|
|
119
|
+
}
|
|
120
|
+
let store = crypto::read_store(&paths.store())?.ok_or_else(|| "vault is not initialized".to_string())?;
|
|
121
|
+
if crypto::store_id(&store) != session.store_id || session.key().is_none() {
|
|
122
|
+
let _ = fs::remove_file(&path);
|
|
123
|
+
return Err("the store changed since this session unlocked — unlock again".into());
|
|
124
|
+
}
|
|
125
|
+
Ok(session)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
pub fn delete(paths: &Paths, token: &str) -> bool {
|
|
129
|
+
fs::remove_file(paths.session_file(token)).is_ok()
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
pub fn delete_all(paths: &Paths) -> usize {
|
|
133
|
+
let dir = paths.sessions();
|
|
134
|
+
let mut removed = 0;
|
|
135
|
+
if let Ok(entries) = fs::read_dir(&dir) {
|
|
136
|
+
for entry in entries.flatten() {
|
|
137
|
+
let path = entry.path();
|
|
138
|
+
if path.extension().and_then(|e| e.to_str()) == Some("json") && fs::remove_file(&path).is_ok() {
|
|
139
|
+
removed += 1;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
removed
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// Remove tokens that already expired, so a tmpfs-less machine does not keep
|
|
147
|
+
/// dead keys around. Called on unlock and lock.
|
|
148
|
+
pub fn sweep(paths: &Paths) -> usize {
|
|
149
|
+
let dir = paths.sessions();
|
|
150
|
+
let mut removed = 0;
|
|
151
|
+
if let Ok(entries) = fs::read_dir(&dir) {
|
|
152
|
+
for entry in entries.flatten() {
|
|
153
|
+
let path = entry.path();
|
|
154
|
+
if path.extension().and_then(|e| e.to_str()) != Some("json") {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
let stale = fs::read_to_string(&path)
|
|
158
|
+
.ok()
|
|
159
|
+
.and_then(|text| serde_json::from_str::<Session>(&text).ok())
|
|
160
|
+
.map(|s| s.expired(now_ms()))
|
|
161
|
+
.unwrap_or(true);
|
|
162
|
+
if stale && fs::remove_file(&path).is_ok() {
|
|
163
|
+
removed += 1;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
removed
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
pub fn now_ms() -> i64 {
|
|
171
|
+
chrono::Utc::now().timestamp_millis()
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
pub fn ensure_session_dir(paths: &Paths) -> Result<(), String> {
|
|
175
|
+
fs::create_dir_all(&paths.dir).map_err(|e| format!("cannot create {}: {e}", paths.dir.display()))?;
|
|
176
|
+
let dir = paths.sessions();
|
|
177
|
+
fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
|
178
|
+
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
|
|
179
|
+
let _ = fs::set_permissions(&paths.dir, fs::Permissions::from_mode(0o700));
|
|
180
|
+
Ok(())
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// Held for the duration of a read-modify-write so two agents cannot overwrite
|
|
184
|
+
/// each other's entries. Never held across a dialog.
|
|
185
|
+
pub struct StoreLock {
|
|
186
|
+
file: fs::File,
|
|
187
|
+
path: std::path::PathBuf,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
impl StoreLock {
|
|
191
|
+
pub fn acquire(paths: &Paths) -> Result<Self, String> {
|
|
192
|
+
ensure_session_dir(paths)?;
|
|
193
|
+
let path = paths.store_lock();
|
|
194
|
+
let file = fs::OpenOptions::new()
|
|
195
|
+
.create(true)
|
|
196
|
+
.read(true)
|
|
197
|
+
.write(true)
|
|
198
|
+
.mode(0o600)
|
|
199
|
+
.open(&path)
|
|
200
|
+
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
|
201
|
+
#[cfg(unix)]
|
|
202
|
+
{
|
|
203
|
+
use std::os::unix::io::AsRawFd;
|
|
204
|
+
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
|
|
205
|
+
if rc != 0 {
|
|
206
|
+
return Err(format!("cannot lock {}: {}", path.display(), std::io::Error::last_os_error()));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
Ok(StoreLock { file, path })
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
impl Drop for StoreLock {
|
|
214
|
+
fn drop(&mut self) {
|
|
215
|
+
#[cfg(unix)]
|
|
216
|
+
{
|
|
217
|
+
use std::os::unix::io::AsRawFd;
|
|
218
|
+
unsafe {
|
|
219
|
+
libc::flock(self.file.as_raw_fd(), libc::LOCK_UN);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
let _ = &self.path;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
impl std::fmt::Debug for StoreLock {
|
|
227
|
+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
228
|
+
write!(f, "StoreLock({})", self.path.display())
|
|
229
|
+
}
|
|
230
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
//! The decrypted contents of the store: a plain array of entries, in the same
|
|
2
|
+
//! shape the TypeScript version used, so an existing store.json still reads.
|
|
3
|
+
|
|
4
|
+
use serde::{Deserialize, Serialize};
|
|
5
|
+
|
|
6
|
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
|
7
|
+
pub struct Source {
|
|
8
|
+
pub kind: String,
|
|
9
|
+
pub id: String,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
13
|
+
#[serde(rename_all = "camelCase")]
|
|
14
|
+
pub struct Item {
|
|
15
|
+
pub id: String,
|
|
16
|
+
pub name: String,
|
|
17
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
18
|
+
pub username: Option<String>,
|
|
19
|
+
#[serde(default)]
|
|
20
|
+
pub password: String,
|
|
21
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
22
|
+
pub uris: Option<Vec<String>>,
|
|
23
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
24
|
+
pub notes: Option<String>,
|
|
25
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
26
|
+
pub source: Option<Source>,
|
|
27
|
+
#[serde(rename = "createdAt")]
|
|
28
|
+
pub created_at: String,
|
|
29
|
+
#[serde(rename = "updatedAt")]
|
|
30
|
+
pub updated_at: String,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/// Metadata only: what `list` shows. The password is left out.
|
|
34
|
+
#[derive(Debug, Serialize)]
|
|
35
|
+
pub struct ItemSummary {
|
|
36
|
+
pub name: String,
|
|
37
|
+
pub username: Option<String>,
|
|
38
|
+
pub uris: Vec<String>,
|
|
39
|
+
#[serde(rename = "updatedAt")]
|
|
40
|
+
pub updated_at: String,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
impl From<&Item> for ItemSummary {
|
|
44
|
+
fn from(item: &Item) -> Self {
|
|
45
|
+
ItemSummary {
|
|
46
|
+
name: item.name.clone(),
|
|
47
|
+
username: item.username.clone(),
|
|
48
|
+
uris: item.uris.clone().unwrap_or_default(),
|
|
49
|
+
updated_at: item.updated_at.clone(),
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// One entry to insert or merge, from `ai-vault add`, `save`, or an import.
|
|
55
|
+
#[derive(Debug, Clone, Default, Deserialize)]
|
|
56
|
+
#[serde(rename_all = "camelCase")]
|
|
57
|
+
pub struct Draft {
|
|
58
|
+
#[serde(default)]
|
|
59
|
+
pub id: Option<String>,
|
|
60
|
+
#[serde(default)]
|
|
61
|
+
pub name: String,
|
|
62
|
+
#[serde(default)]
|
|
63
|
+
pub username: Option<String>,
|
|
64
|
+
#[serde(default)]
|
|
65
|
+
pub password: String,
|
|
66
|
+
#[serde(default)]
|
|
67
|
+
pub uris: Option<Vec<String>>,
|
|
68
|
+
#[serde(default)]
|
|
69
|
+
pub notes: Option<String>,
|
|
70
|
+
#[serde(default)]
|
|
71
|
+
pub source: Option<Source>,
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
pub fn now_iso() -> String {
|
|
75
|
+
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
pub fn random_id() -> String {
|
|
79
|
+
let mut buf = [0u8; 8];
|
|
80
|
+
let _ = getrandom::getrandom(&mut buf);
|
|
81
|
+
buf.iter().map(|b| format!("{b:02x}")).collect()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
pub fn find<'a>(items: &'a [Item], name: &str) -> Option<&'a Item> {
|
|
85
|
+
let lower = name.to_lowercase();
|
|
86
|
+
items.iter().find(|i| i.name.to_lowercase() == lower)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
pub fn remove(items: &mut Vec<Item>, name: &str) -> bool {
|
|
90
|
+
let lower = name.to_lowercase();
|
|
91
|
+
match items.iter().position(|i| i.name.to_lowercase() == lower) {
|
|
92
|
+
Some(idx) => {
|
|
93
|
+
items.remove(idx);
|
|
94
|
+
true
|
|
95
|
+
}
|
|
96
|
+
None => false,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// An entry is matched by local id, else by its import source, else by name.
|
|
101
|
+
/// Returns `true` when a new entry was pushed.
|
|
102
|
+
pub fn apply(items: &mut Vec<Item>, draft: Draft, now: &str) -> bool {
|
|
103
|
+
let lower = draft.name.to_lowercase();
|
|
104
|
+
let existing_idx = if let Some(id) = draft.id.as_deref() {
|
|
105
|
+
items.iter().position(|i| i.id == id)
|
|
106
|
+
} else {
|
|
107
|
+
let by_source = draft.source.as_ref().and_then(|source| {
|
|
108
|
+
items
|
|
109
|
+
.iter()
|
|
110
|
+
.position(|i| i.source.as_ref().is_some_and(|s| s.kind == source.kind && s.id == source.id))
|
|
111
|
+
});
|
|
112
|
+
by_source.or_else(|| items.iter().position(|i| i.name.to_lowercase() == lower))
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
if let Some(idx) = existing_idx {
|
|
116
|
+
let before = items[idx].name.clone();
|
|
117
|
+
// Matched by source under a new name: keep the old one if another
|
|
118
|
+
// entry already carries the new name.
|
|
119
|
+
let keep_old_name = before != draft.name
|
|
120
|
+
&& items.iter().enumerate().any(|(i, other)| i != idx && other.name.to_lowercase() == lower);
|
|
121
|
+
let item = &mut items[idx];
|
|
122
|
+
item.name = draft.name.clone();
|
|
123
|
+
if draft.username.is_some() {
|
|
124
|
+
item.username = draft.username.clone();
|
|
125
|
+
}
|
|
126
|
+
if !draft.password.is_empty() {
|
|
127
|
+
item.password = draft.password.clone();
|
|
128
|
+
}
|
|
129
|
+
if draft.uris.is_some() {
|
|
130
|
+
item.uris = draft.uris.clone();
|
|
131
|
+
}
|
|
132
|
+
if draft.notes.is_some() {
|
|
133
|
+
item.notes = draft.notes.clone();
|
|
134
|
+
}
|
|
135
|
+
if draft.source.is_some() {
|
|
136
|
+
item.source = draft.source.clone();
|
|
137
|
+
}
|
|
138
|
+
if keep_old_name {
|
|
139
|
+
item.name = before;
|
|
140
|
+
}
|
|
141
|
+
item.updated_at = now.to_string();
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
items.push(Item {
|
|
146
|
+
id: draft.id.unwrap_or_else(random_id),
|
|
147
|
+
name: draft.name,
|
|
148
|
+
username: draft.username,
|
|
149
|
+
password: draft.password,
|
|
150
|
+
uris: draft.uris,
|
|
151
|
+
notes: draft.notes,
|
|
152
|
+
source: draft.source,
|
|
153
|
+
created_at: now.to_string(),
|
|
154
|
+
updated_at: now.to_string(),
|
|
155
|
+
});
|
|
156
|
+
true
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
#[cfg(test)]
|
|
160
|
+
mod tests {
|
|
161
|
+
use super::*;
|
|
162
|
+
|
|
163
|
+
fn draft(name: &str, password: &str) -> Draft {
|
|
164
|
+
Draft {
|
|
165
|
+
name: name.into(),
|
|
166
|
+
password: password.into(),
|
|
167
|
+
..Default::default()
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
#[test]
|
|
172
|
+
fn inserts_and_updates_by_name() {
|
|
173
|
+
let mut items = Vec::new();
|
|
174
|
+
assert!(apply(&mut items, draft("GitHub", "a"), "t1"));
|
|
175
|
+
assert!(!apply(&mut items, draft("github", "b"), "t2"));
|
|
176
|
+
assert_eq!(items.len(), 1);
|
|
177
|
+
assert_eq!(items[0].password, "b");
|
|
178
|
+
assert_eq!(items[0].created_at, "t1");
|
|
179
|
+
assert_eq!(items[0].updated_at, "t2");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
#[test]
|
|
183
|
+
fn updates_by_source_after_a_rename() {
|
|
184
|
+
let mut items = Vec::new();
|
|
185
|
+
let mut first = draft("GitHub", "a");
|
|
186
|
+
first.source = Some(Source { kind: "bitwarden".into(), id: "abc".into() });
|
|
187
|
+
apply(&mut items, first, "t1");
|
|
188
|
+
let mut renamed = draft("GitHub Personal", "a2");
|
|
189
|
+
renamed.source = Some(Source { kind: "bitwarden".into(), id: "abc".into() });
|
|
190
|
+
assert!(!apply(&mut items, renamed, "t2"));
|
|
191
|
+
assert_eq!(items.len(), 1);
|
|
192
|
+
assert_eq!(items[0].name, "GitHub Personal");
|
|
193
|
+
assert_eq!(items[0].password, "a2");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
#[test]
|
|
197
|
+
fn rename_does_not_steal_another_entrys_name() {
|
|
198
|
+
let mut items = Vec::new();
|
|
199
|
+
apply(&mut items, draft("A", "1"), "t");
|
|
200
|
+
let mut second = draft("B", "2");
|
|
201
|
+
second.source = Some(Source { kind: "bitwarden".into(), id: "x".into() });
|
|
202
|
+
apply(&mut items, second, "t");
|
|
203
|
+
let mut renamed = draft("A", "3");
|
|
204
|
+
renamed.source = Some(Source { kind: "bitwarden".into(), id: "x".into() });
|
|
205
|
+
apply(&mut items, renamed, "t");
|
|
206
|
+
let names: Vec<_> = items.iter().map(|i| i.name.clone()).collect();
|
|
207
|
+
assert_eq!(names, vec!["A", "B"]);
|
|
208
|
+
assert_eq!(items[1].password, "3");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
#[test]
|
|
212
|
+
fn matches_case_insensitively() {
|
|
213
|
+
let mut items = Vec::new();
|
|
214
|
+
apply(&mut items, draft("GitHub", "a"), "t");
|
|
215
|
+
assert!(find(&items, "github").is_some());
|
|
216
|
+
assert!(remove(&mut items, "GITHUB"));
|
|
217
|
+
assert!(items.is_empty());
|
|
218
|
+
}
|
|
219
|
+
}
|
package/install.sh
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Build the ai-vault CLI and put it on PATH. The extension only calls this
|
|
3
|
+
# binary, so one install serves pi, omp, and anything else on the machine.
|
|
4
|
+
#
|
|
5
|
+
# ./install.sh -> ~/.local/bin/ai-vault
|
|
6
|
+
# ./install.sh /usr/local/bin -> another directory
|
|
7
|
+
set -euo pipefail
|
|
8
|
+
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
|
9
|
+
DEST="${1:-$HOME/.local/bin}"
|
|
10
|
+
|
|
11
|
+
command -v cargo >/dev/null || { echo "cargo is required (https://rustup.rs)" >&2; exit 1; }
|
|
12
|
+
cargo build --release --manifest-path "$ROOT/Cargo.toml"
|
|
13
|
+
|
|
14
|
+
mkdir -p "$DEST"
|
|
15
|
+
install -m 755 "$ROOT/target/release/ai-vault" "$DEST/ai-vault"
|
|
16
|
+
echo "installed $("$DEST/ai-vault" --version) -> $DEST/ai-vault"
|
|
17
|
+
|
|
18
|
+
case ":$PATH:" in
|
|
19
|
+
*":$DEST:"*) ;;
|
|
20
|
+
*) echo "note: $DEST is not on PATH; add it so the pi/omp extension can find ai-vault" >&2 ;;
|
|
21
|
+
esac
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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.",
|
|
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
|
+
"ai-vault",
|
|
17
|
+
"vault",
|
|
18
|
+
"secrets",
|
|
19
|
+
"password-store",
|
|
20
|
+
"cli",
|
|
21
|
+
"rust",
|
|
22
|
+
"omp-package",
|
|
23
|
+
"pi",
|
|
24
|
+
"pi-coding-agent",
|
|
25
|
+
"extension",
|
|
26
|
+
"security",
|
|
27
|
+
"omp"
|
|
28
|
+
],
|
|
29
|
+
"bin": {
|
|
30
|
+
"ai-vault": "./bin/ai-vault.cjs"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"optionalDependencies": {
|
|
36
|
+
"@xiaolikt/ai-vault-linux-x64": "0.4.1"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"bin",
|
|
40
|
+
"src",
|
|
41
|
+
"crates",
|
|
42
|
+
"Cargo.toml",
|
|
43
|
+
"Cargo.lock",
|
|
44
|
+
"install.sh",
|
|
45
|
+
"test",
|
|
46
|
+
"tests",
|
|
47
|
+
"README.md",
|
|
48
|
+
"LICENSE"
|
|
49
|
+
],
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build:cli": "cargo build --release",
|
|
52
|
+
"stage:npm": "bash scripts/stage-npm.sh",
|
|
53
|
+
"pretest": "cargo build --release",
|
|
54
|
+
"test": "node --import tsx --test tests/*.test.mjs",
|
|
55
|
+
"test:cli": "bash test/cli.sh",
|
|
56
|
+
"test:npm": "bash test/npm.sh",
|
|
57
|
+
"test:cargo": "cargo test",
|
|
58
|
+
"test:smoke": "bash test/smoke.sh",
|
|
59
|
+
"typecheck": "tsc --noEmit"
|
|
60
|
+
},
|
|
61
|
+
"peerDependencies": {
|
|
62
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
63
|
+
"typebox": "1.3.27"
|
|
64
|
+
},
|
|
65
|
+
"devDependencies": {
|
|
66
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
67
|
+
"@types/node": "^24.0.0",
|
|
68
|
+
"tsx": "^4.23.15",
|
|
69
|
+
"typebox": "1.3.27",
|
|
70
|
+
"typescript": "^5.9.0"
|
|
71
|
+
},
|
|
72
|
+
"pi": {
|
|
73
|
+
"extensions": [
|
|
74
|
+
"./src/index.ts"
|
|
75
|
+
]
|
|
76
|
+
}
|
|
77
|
+
}
|