@xiaolikt/ai-vault 0.0.0-stage → 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.
- package/Cargo.lock +784 -0
- package/Cargo.toml +8 -0
- package/LICENSE +21 -0
- package/README.md +244 -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 +1129 -0
- package/crates/ai-vault/src/config.rs +77 -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 +22 -0
- package/crates/ai-vault/src/paths.rs +68 -0
- package/crates/ai-vault/src/session.rs +280 -0
- package/crates/ai-vault/src/store.rs +219 -0
- package/install.sh +21 -0
- package/package.json +76 -5
- package/packages/pi-ai-vault/README.md +62 -0
- package/packages/pi-ai-vault/package.json +47 -0
- package/packages/pi-ai-vault/src/bitwarden.ts +1482 -0
- package/packages/pi-ai-vault/src/cli.ts +171 -0
- package/packages/pi-ai-vault/src/host.ts +76 -0
- package/packages/pi-ai-vault/src/import-map.ts +91 -0
- package/packages/pi-ai-vault/src/index.ts +976 -0
- package/packages/pi-ai-vault/src/prompt.ts +195 -0
- package/packages/pi-ai-vault/src/scrub.ts +157 -0
- package/test/cli.sh +135 -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 +131 -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 +51 -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 +217 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
//! Turning external payloads into entries: Bitwarden JSON exports and the
|
|
2
|
+
//! draft array the pi/omp extension sends after reading `bw`.
|
|
3
|
+
|
|
4
|
+
use serde_json::Value;
|
|
5
|
+
|
|
6
|
+
use crate::store::{Draft, Source};
|
|
7
|
+
|
|
8
|
+
const MAX_NAME: usize = 200;
|
|
9
|
+
|
|
10
|
+
fn as_uris(login: &serde_json::Map<String, Value>) -> Vec<String> {
|
|
11
|
+
match login.get("uris").and_then(|u| u.as_array()) {
|
|
12
|
+
Some(list) => list
|
|
13
|
+
.iter()
|
|
14
|
+
.filter_map(|entry| entry.get("uri").and_then(|u| u.as_str()))
|
|
15
|
+
.filter(|uri| !uri.is_empty())
|
|
16
|
+
.map(str::to_string)
|
|
17
|
+
.collect(),
|
|
18
|
+
None => Vec::new(),
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
fn sanitized_name(raw: &str) -> String {
|
|
23
|
+
let cleaned = raw.replace(['\r', '\n'], " ");
|
|
24
|
+
let cleaned = cleaned.trim();
|
|
25
|
+
if cleaned.is_empty() {
|
|
26
|
+
return "unnamed".to_string();
|
|
27
|
+
}
|
|
28
|
+
cleaned.chars().take(MAX_NAME).collect()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// Bitwarden export (array or `{ "items": [...] }`) -> drafts. Login items
|
|
32
|
+
/// without a password are skipped; names are sorted, then made unique with
|
|
33
|
+
/// `Name (2)`, `Name (3)`, … Each draft keeps its Bitwarden id so a re-import
|
|
34
|
+
/// updates the same row after a rename.
|
|
35
|
+
pub fn from_bitwarden(raw: &Value) -> Result<Vec<Draft>, String> {
|
|
36
|
+
let items = match raw {
|
|
37
|
+
Value::Array(items) => items,
|
|
38
|
+
Value::Object(rec) => {
|
|
39
|
+
if rec.get("encrypted").and_then(Value::as_bool) == Some(true) {
|
|
40
|
+
return Err("This is an encrypted Bitwarden export. Use `bw export --format json` (unencrypted) or /vault import-bw.".into());
|
|
41
|
+
}
|
|
42
|
+
match rec.get("items") {
|
|
43
|
+
Some(Value::Array(items)) => items,
|
|
44
|
+
_ => return Err("Not a Bitwarden export: expected an array of items or an object with `items`.".into()),
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
_ => return Err("Not a Bitwarden export: expected an array of items or an object with `items`.".into()),
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
let mut drafts: Vec<Draft> = Vec::new();
|
|
51
|
+
for item in items {
|
|
52
|
+
let Some(rec) = item.as_object() else { continue };
|
|
53
|
+
let Some(login) = rec.get("login").and_then(Value::as_object) else { continue };
|
|
54
|
+
let password = login.get("password").and_then(Value::as_str).unwrap_or("");
|
|
55
|
+
if password.is_empty() {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
let username = rec
|
|
59
|
+
.get("login")
|
|
60
|
+
.and_then(|l| l.get("username"))
|
|
61
|
+
.and_then(Value::as_str)
|
|
62
|
+
.filter(|u| !u.is_empty())
|
|
63
|
+
.map(str::to_string);
|
|
64
|
+
let notes = rec
|
|
65
|
+
.get("notes")
|
|
66
|
+
.and_then(Value::as_str)
|
|
67
|
+
.filter(|n| !n.is_empty())
|
|
68
|
+
.map(str::to_string);
|
|
69
|
+
let source = rec
|
|
70
|
+
.get("id")
|
|
71
|
+
.and_then(Value::as_str)
|
|
72
|
+
.filter(|id| !id.is_empty())
|
|
73
|
+
.map(|id| Source { kind: "bitwarden".into(), id: id.to_string() });
|
|
74
|
+
drafts.push(Draft {
|
|
75
|
+
id: None,
|
|
76
|
+
name: sanitized_name(rec.get("name").and_then(Value::as_str).unwrap_or("")),
|
|
77
|
+
username,
|
|
78
|
+
password: password.to_string(),
|
|
79
|
+
uris: Some(as_uris(login)),
|
|
80
|
+
notes,
|
|
81
|
+
source,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
drafts.sort_by(|a, b| {
|
|
86
|
+
a.name
|
|
87
|
+
.to_lowercase()
|
|
88
|
+
.cmp(&b.name.to_lowercase())
|
|
89
|
+
.then_with(|| a.username.clone().unwrap_or_default().to_lowercase().cmp(&b.username.clone().unwrap_or_default().to_lowercase()))
|
|
90
|
+
.then_with(|| {
|
|
91
|
+
let ax = a.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default().to_lowercase();
|
|
92
|
+
let bx = b.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default().to_lowercase();
|
|
93
|
+
ax.cmp(&bx)
|
|
94
|
+
})
|
|
95
|
+
});
|
|
96
|
+
let mut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
|
97
|
+
for item in &mut drafts {
|
|
98
|
+
let count = seen.entry(item.name.to_lowercase()).or_insert(0);
|
|
99
|
+
*count += 1;
|
|
100
|
+
if *count > 1 {
|
|
101
|
+
item.name = format!("{} ({count})", item.name);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
Ok(drafts)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
pub fn parse_bitwarden_json(text: &str) -> Result<Vec<Draft>, String> {
|
|
108
|
+
let value: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?;
|
|
109
|
+
from_bitwarden(&value)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// The `save` payload: an array of drafts, or `{ "items": [...] }`.
|
|
113
|
+
pub fn parse_drafts(text: &str) -> Result<Vec<Draft>, String> {
|
|
114
|
+
let value: Value = serde_json::from_str(text).map_err(|e| format!("invalid JSON: {e}"))?;
|
|
115
|
+
let items = match value {
|
|
116
|
+
Value::Array(items) => items,
|
|
117
|
+
Value::Object(rec) => match rec.get("items") {
|
|
118
|
+
Some(Value::Array(items)) => items.clone(),
|
|
119
|
+
_ => return Err("expected a JSON array of entries".into()),
|
|
120
|
+
},
|
|
121
|
+
_ => return Err("expected a JSON array of entries".into()),
|
|
122
|
+
};
|
|
123
|
+
let mut drafts = Vec::with_capacity(items.len());
|
|
124
|
+
for item in items {
|
|
125
|
+
let draft: Draft = serde_json::from_value(item).map_err(|e| format!("bad entry: {e}"))?;
|
|
126
|
+
if draft.name.trim().is_empty() {
|
|
127
|
+
return Err("every entry needs a name".into());
|
|
128
|
+
}
|
|
129
|
+
drafts.push(draft);
|
|
130
|
+
}
|
|
131
|
+
Ok(drafts)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
#[cfg(test)]
|
|
135
|
+
mod tests {
|
|
136
|
+
use super::*;
|
|
137
|
+
|
|
138
|
+
#[test]
|
|
139
|
+
fn skips_logins_without_a_password() {
|
|
140
|
+
let raw = serde_json::json!([
|
|
141
|
+
{ "id": "1", "name": "Good", "login": { "username": "u", "password": "p", "uris": [{ "uri": "https://a" }] } },
|
|
142
|
+
{ "id": "2", "name": "NoPw", "login": { "username": "u" } },
|
|
143
|
+
{ "id": "3", "name": "Note only", "notes": "x" }
|
|
144
|
+
]);
|
|
145
|
+
let drafts = from_bitwarden(&raw).unwrap();
|
|
146
|
+
assert_eq!(drafts.len(), 1);
|
|
147
|
+
assert_eq!(drafts[0].name, "Good");
|
|
148
|
+
assert_eq!(drafts[0].uris.as_ref().unwrap()[0], "https://a");
|
|
149
|
+
assert_eq!(drafts[0].source.as_ref().unwrap().id, "1");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
#[test]
|
|
153
|
+
fn renames_duplicates_and_sorts() {
|
|
154
|
+
let raw = serde_json::json!([
|
|
155
|
+
{ "name": "b", "login": { "password": "1" } },
|
|
156
|
+
{ "name": "b", "login": { "password": "2" } },
|
|
157
|
+
{ "name": "a", "login": { "password": "3" } }
|
|
158
|
+
]);
|
|
159
|
+
let names: Vec<_> = from_bitwarden(&raw).unwrap().into_iter().map(|d| d.name).collect();
|
|
160
|
+
assert_eq!(names, vec!["a", "b", "b (2)"]);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
#[test]
|
|
164
|
+
fn rejects_encrypted_exports() {
|
|
165
|
+
let raw = serde_json::json!({ "encrypted": true, "data": "..." });
|
|
166
|
+
assert!(from_bitwarden(&raw).unwrap_err().contains("encrypted"));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
#[test]
|
|
170
|
+
fn parses_draft_payloads() {
|
|
171
|
+
let drafts = parse_drafts(r#"[{"name":"x","username":"u","password":"p","uris":["https://x"],"source":{"kind":"bitwarden","id":"9"}}]"#).unwrap();
|
|
172
|
+
assert_eq!(drafts.len(), 1);
|
|
173
|
+
assert_eq!(drafts[0].source.as_ref().unwrap().id, "9");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//! ai-vault — one machine-wide encrypted secret store, shared by every agent.
|
|
2
|
+
//!
|
|
3
|
+
//! The store lives at `~/.ai-vault/store.json` (override with `AI_VAULT_DIR`),
|
|
4
|
+
//! encrypted with ChaCha20-Poly1305, keyed by scrypt from the master password.
|
|
5
|
+
//! An agent (pi, omp, anything else) never holds the master password: it asks
|
|
6
|
+
//! this binary to unlock, gets a short-lived session token, and passes that
|
|
7
|
+
//! token back on every later call.
|
|
8
|
+
|
|
9
|
+
mod audit;
|
|
10
|
+
mod cli;
|
|
11
|
+
mod config;
|
|
12
|
+
mod crypto;
|
|
13
|
+
mod dialog;
|
|
14
|
+
mod import;
|
|
15
|
+
mod paths;
|
|
16
|
+
mod session;
|
|
17
|
+
mod store;
|
|
18
|
+
|
|
19
|
+
fn main() {
|
|
20
|
+
let code = cli::run();
|
|
21
|
+
std::process::exit(code);
|
|
22
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
/// 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
|
+
/// Shared advisory lock for read-modify-write of the store file.
|
|
46
|
+
pub fn store_lock(&self) -> PathBuf {
|
|
47
|
+
self.dir.join("store.lock")
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// Session tokens hold key material, so they prefer tmpfs when there is one:
|
|
51
|
+
/// they vanish at logout instead of lying on disk.
|
|
52
|
+
pub fn sessions(&self) -> PathBuf {
|
|
53
|
+
match env::var_os("XDG_RUNTIME_DIR") {
|
|
54
|
+
Some(runtime) if !runtime.is_empty() && self.dir == Paths::resolve(None).dir => {
|
|
55
|
+
PathBuf::from(runtime).join("ai-vault").join("sessions")
|
|
56
|
+
}
|
|
57
|
+
_ => self.dir.join("sessions"),
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
pub fn session_file(&self, token: &str) -> PathBuf {
|
|
62
|
+
self.sessions().join(format!("{token}.json"))
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
pub fn home() -> PathBuf {
|
|
67
|
+
env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| Path::new(".").to_path_buf())
|
|
68
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
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
|
+
/// 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>,
|
|
37
|
+
#[serde(rename = "storeId")]
|
|
38
|
+
pub store_id: String,
|
|
39
|
+
pub salt: String,
|
|
40
|
+
#[serde(default)]
|
|
41
|
+
pub kdf: Option<Kdf>,
|
|
42
|
+
pub key: String,
|
|
43
|
+
/// entry name (lowercase) -> grant expiry epoch ms
|
|
44
|
+
#[serde(default)]
|
|
45
|
+
pub grants: BTreeMap<String, i64>,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
impl Session {
|
|
49
|
+
pub fn new(requester: &str, idle_ms: i64, expires_at: Option<i64>, store: &crypto::StoreFile, key: &[u8; 32]) -> Self {
|
|
50
|
+
let now = now_ms();
|
|
51
|
+
Session {
|
|
52
|
+
token: crate::store::random_id() + &crate::store::random_id(),
|
|
53
|
+
requester: requester.to_string(),
|
|
54
|
+
created_at: now,
|
|
55
|
+
last_active: now,
|
|
56
|
+
idle_ms,
|
|
57
|
+
expires_at,
|
|
58
|
+
store_id: crypto::store_id(store),
|
|
59
|
+
salt: store.salt.clone(),
|
|
60
|
+
kdf: Some(store.kdf()),
|
|
61
|
+
key: B64.encode(key),
|
|
62
|
+
grants: BTreeMap::new(),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
pub fn key(&self) -> Option<Zeroizing<[u8; 32]>> {
|
|
67
|
+
let raw = B64.decode(self.key.as_bytes()).ok()?;
|
|
68
|
+
if raw.len() != 32 {
|
|
69
|
+
return None;
|
|
70
|
+
}
|
|
71
|
+
let mut key = Zeroizing::new([0u8; 32]);
|
|
72
|
+
key.copy_from_slice(&raw);
|
|
73
|
+
Some(key)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// A deadline beats the idle window; `idleMs: 0` with no deadline means
|
|
77
|
+
/// "never expires on its own".
|
|
78
|
+
pub fn expired(&self, now: i64) -> bool {
|
|
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
|
|
83
|
+
}
|
|
84
|
+
|
|
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))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// Drop grants that ran out. Returns true when anything was removed.
|
|
91
|
+
pub fn prune_grants(&mut self, now: i64) -> bool {
|
|
92
|
+
let before = self.grants.len();
|
|
93
|
+
self.grants.retain(|_, until| *until > now);
|
|
94
|
+
before != self.grants.len()
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
pub fn grant(&self, name: &str, now: i64) -> Option<i64> {
|
|
98
|
+
self.grants
|
|
99
|
+
.get(&name.to_lowercase())
|
|
100
|
+
.copied()
|
|
101
|
+
.filter(|until| *until > now)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
pub fn save(&self, paths: &Paths) -> Result<(), String> {
|
|
105
|
+
let dir = paths.sessions();
|
|
106
|
+
fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
|
107
|
+
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
|
|
108
|
+
let text = serde_json::to_vec(self).map_err(|e| format!("cannot serialize session: {e}"))?;
|
|
109
|
+
crypto::write_atomic(&paths.session_file(&self.token), &text)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/// Load a token for the given store. Missing, expired, or stale tokens are
|
|
114
|
+
/// removed and reported as locked so the caller unlocks again.
|
|
115
|
+
pub fn load(paths: &Paths, token: &str) -> Result<Session, String> {
|
|
116
|
+
let path = paths.session_file(token);
|
|
117
|
+
let text = match fs::read_to_string(&path) {
|
|
118
|
+
Ok(text) => text,
|
|
119
|
+
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
|
120
|
+
return Err("vault is locked (no unlock in this session)".into())
|
|
121
|
+
}
|
|
122
|
+
Err(e) => return Err(format!("cannot read session {}: {e}", path.display())),
|
|
123
|
+
};
|
|
124
|
+
let session: Session = serde_json::from_str(&text)
|
|
125
|
+
.map_err(|_| "session token is corrupt — unlock again".to_string())?;
|
|
126
|
+
let now = now_ms();
|
|
127
|
+
if session.expired(now) {
|
|
128
|
+
let _ = fs::remove_file(&path);
|
|
129
|
+
return Err("vault locked itself after 10 minutes idle — unlock again".into());
|
|
130
|
+
}
|
|
131
|
+
let store = crypto::read_store(&paths.store())?.ok_or_else(|| "vault is not initialized".to_string())?;
|
|
132
|
+
if crypto::store_id(&store) != session.store_id || session.key().is_none() {
|
|
133
|
+
let _ = fs::remove_file(&path);
|
|
134
|
+
return Err("the store changed since this session unlocked — unlock again".into());
|
|
135
|
+
}
|
|
136
|
+
Ok(session)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
pub fn delete(paths: &Paths, token: &str) -> bool {
|
|
140
|
+
fs::remove_file(paths.session_file(token)).is_ok()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
pub fn delete_all(paths: &Paths) -> usize {
|
|
144
|
+
let dir = paths.sessions();
|
|
145
|
+
let mut removed = 0;
|
|
146
|
+
if let Ok(entries) = fs::read_dir(&dir) {
|
|
147
|
+
for entry in entries.flatten() {
|
|
148
|
+
let path = entry.path();
|
|
149
|
+
if path.extension().and_then(|e| e.to_str()) == Some("json") && fs::remove_file(&path).is_ok() {
|
|
150
|
+
removed += 1;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
removed
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/// Remove tokens that already expired, so a tmpfs-less machine does not keep
|
|
158
|
+
/// dead keys around. Called on unlock and lock.
|
|
159
|
+
pub fn sweep(paths: &Paths) -> usize {
|
|
160
|
+
let dir = paths.sessions();
|
|
161
|
+
let mut removed = 0;
|
|
162
|
+
if let Ok(entries) = fs::read_dir(&dir) {
|
|
163
|
+
for entry in entries.flatten() {
|
|
164
|
+
let path = entry.path();
|
|
165
|
+
if path.extension().and_then(|e| e.to_str()) != Some("json") {
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
let stale = fs::read_to_string(&path)
|
|
169
|
+
.ok()
|
|
170
|
+
.and_then(|text| serde_json::from_str::<Session>(&text).ok())
|
|
171
|
+
.map(|s| s.expired(now_ms()))
|
|
172
|
+
.unwrap_or(true);
|
|
173
|
+
if stale && fs::remove_file(&path).is_ok() {
|
|
174
|
+
removed += 1;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
removed
|
|
179
|
+
}
|
|
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
|
+
|
|
220
|
+
pub fn now_ms() -> i64 {
|
|
221
|
+
chrono::Utc::now().timestamp_millis()
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
pub fn ensure_session_dir(paths: &Paths) -> Result<(), String> {
|
|
225
|
+
fs::create_dir_all(&paths.dir).map_err(|e| format!("cannot create {}: {e}", paths.dir.display()))?;
|
|
226
|
+
let dir = paths.sessions();
|
|
227
|
+
fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
|
228
|
+
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
|
|
229
|
+
let _ = fs::set_permissions(&paths.dir, fs::Permissions::from_mode(0o700));
|
|
230
|
+
Ok(())
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// Held for the duration of a read-modify-write so two agents cannot overwrite
|
|
234
|
+
/// each other's entries. Never held across a dialog.
|
|
235
|
+
pub struct StoreLock {
|
|
236
|
+
file: fs::File,
|
|
237
|
+
path: std::path::PathBuf,
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
impl StoreLock {
|
|
241
|
+
pub fn acquire(paths: &Paths) -> Result<Self, String> {
|
|
242
|
+
ensure_session_dir(paths)?;
|
|
243
|
+
let path = paths.store_lock();
|
|
244
|
+
let file = fs::OpenOptions::new()
|
|
245
|
+
.create(true)
|
|
246
|
+
.read(true)
|
|
247
|
+
.write(true)
|
|
248
|
+
.mode(0o600)
|
|
249
|
+
.open(&path)
|
|
250
|
+
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
|
251
|
+
#[cfg(unix)]
|
|
252
|
+
{
|
|
253
|
+
use std::os::unix::io::AsRawFd;
|
|
254
|
+
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
|
|
255
|
+
if rc != 0 {
|
|
256
|
+
return Err(format!("cannot lock {}: {}", path.display(), std::io::Error::last_os_error()));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
Ok(StoreLock { file, path })
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
impl Drop for StoreLock {
|
|
264
|
+
fn drop(&mut self) {
|
|
265
|
+
#[cfg(unix)]
|
|
266
|
+
{
|
|
267
|
+
use std::os::unix::io::AsRawFd;
|
|
268
|
+
unsafe {
|
|
269
|
+
libc::flock(self.file.as_raw_fd(), libc::LOCK_UN);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
let _ = &self.path;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
impl std::fmt::Debug for StoreLock {
|
|
277
|
+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
278
|
+
write!(f, "StoreLock({})", self.path.display())
|
|
279
|
+
}
|
|
280
|
+
}
|