@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,1129 @@
|
|
|
1
|
+
//! Command line surface. Every subcommand is one process: read the store,
|
|
2
|
+
//! prove the session token, do one thing, exit. The pi/omp extension calls
|
|
3
|
+
//! these commands and never links against the encryption itself.
|
|
4
|
+
|
|
5
|
+
use std::io::{self, BufRead, Read};
|
|
6
|
+
use std::os::unix::fs::PermissionsExt;
|
|
7
|
+
use std::path::PathBuf;
|
|
8
|
+
|
|
9
|
+
use clap::{Parser, Subcommand};
|
|
10
|
+
use serde_json::json;
|
|
11
|
+
|
|
12
|
+
use crate::config::{self, UnlockMode, UnlockPolicy};
|
|
13
|
+
use crate::crypto::{self, Kdf};
|
|
14
|
+
use crate::dialog::{self, Answer};
|
|
15
|
+
use crate::import;
|
|
16
|
+
use crate::paths::{Paths, GRANT_MS_DEFAULT, GRANT_MS_MAX, IDLE_MS_DEFAULT};
|
|
17
|
+
use crate::session::{self, Session, StoreLock};
|
|
18
|
+
use crate::store::{self, Draft, Item};
|
|
19
|
+
use crate::{audit, store::ItemSummary};
|
|
20
|
+
|
|
21
|
+
#[derive(Parser, Debug)]
|
|
22
|
+
#[command(
|
|
23
|
+
name = "ai-vault",
|
|
24
|
+
version,
|
|
25
|
+
about = "Machine-wide encrypted secret store shared by AI coding agents",
|
|
26
|
+
long_about = "One encrypted store per machine (~/.ai-vault), shared by every agent.\n\
|
|
27
|
+
The master password goes through a desktop dialog, never through the\n\
|
|
28
|
+
conversation. `unlock` returns a short-lived token; later calls pass it\n\
|
|
29
|
+
back with --token (or AI_VAULT_TOKEN)."
|
|
30
|
+
)]
|
|
31
|
+
struct Cli {
|
|
32
|
+
/// Store directory (default: $AI_VAULT_DIR or ~/.ai-vault)
|
|
33
|
+
#[arg(long, global = true, env = "AI_VAULT_DIR", value_name = "DIR")]
|
|
34
|
+
dir: Option<PathBuf>,
|
|
35
|
+
/// Machine-readable JSON on stdout
|
|
36
|
+
#[arg(long, global = true)]
|
|
37
|
+
json: bool,
|
|
38
|
+
#[command(subcommand)]
|
|
39
|
+
cmd: Cmd,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#[derive(Subcommand, Debug)]
|
|
43
|
+
enum Cmd {
|
|
44
|
+
/// Print the store directory
|
|
45
|
+
Path,
|
|
46
|
+
/// Create the store and a fresh session (prompts for a new master password)
|
|
47
|
+
Init {
|
|
48
|
+
/// Read the password from stdin instead of a dialog
|
|
49
|
+
#[arg(long)]
|
|
50
|
+
password_stdin: bool,
|
|
51
|
+
/// Who is unlocking (written to the audit log)
|
|
52
|
+
#[arg(long, default_value = "cli")]
|
|
53
|
+
requester: String,
|
|
54
|
+
/// Idle minutes before the session locks itself
|
|
55
|
+
#[arg(long, value_name = "MIN")]
|
|
56
|
+
idle_min: Option<i64>,
|
|
57
|
+
},
|
|
58
|
+
/// Unlock the store and print a session token
|
|
59
|
+
Unlock {
|
|
60
|
+
/// Read the password from stdin instead of a dialog
|
|
61
|
+
#[arg(long)]
|
|
62
|
+
password_stdin: bool,
|
|
63
|
+
/// Who is unlocking (written to the audit log and the confirm window)
|
|
64
|
+
#[arg(long, default_value = "cli")]
|
|
65
|
+
requester: String,
|
|
66
|
+
/// Idle minutes before the session locks itself
|
|
67
|
+
#[arg(long, value_name = "MIN")]
|
|
68
|
+
idle_min: Option<i64>,
|
|
69
|
+
},
|
|
70
|
+
/// Show or change how often the master password is asked for
|
|
71
|
+
Mode {
|
|
72
|
+
/// "get" or "set"
|
|
73
|
+
#[arg(default_value = "get")]
|
|
74
|
+
action: String,
|
|
75
|
+
/// never | time | session (for `set`)
|
|
76
|
+
value: Option<String>,
|
|
77
|
+
/// Hours between prompts in `time` mode
|
|
78
|
+
#[arg(long, value_name = "HOURS")]
|
|
79
|
+
hours: Option<i64>,
|
|
80
|
+
/// Read the master password from stdin (changing the mode needs it)
|
|
81
|
+
#[arg(long)]
|
|
82
|
+
password_stdin: bool,
|
|
83
|
+
},
|
|
84
|
+
/// Session state, item count, and remaining read grants
|
|
85
|
+
Status {
|
|
86
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
87
|
+
token: Option<String>,
|
|
88
|
+
},
|
|
89
|
+
/// Drop one session token, or every session with --all
|
|
90
|
+
Lock {
|
|
91
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
92
|
+
token: Option<String>,
|
|
93
|
+
#[arg(long)]
|
|
94
|
+
all: bool,
|
|
95
|
+
},
|
|
96
|
+
/// Entry metadata only (name, username, URIs) — no passwords
|
|
97
|
+
List {
|
|
98
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
99
|
+
token: Option<String>,
|
|
100
|
+
},
|
|
101
|
+
/// Read one entry; the user approves a window unless a grant is live
|
|
102
|
+
Get {
|
|
103
|
+
name: String,
|
|
104
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
105
|
+
token: Option<String>,
|
|
106
|
+
/// Why the secret is needed (shown in the confirm window)
|
|
107
|
+
#[arg(long)]
|
|
108
|
+
reason: Option<String>,
|
|
109
|
+
/// Read the approve/deny answer from stdin (host UI already asked)
|
|
110
|
+
#[arg(long)]
|
|
111
|
+
answer_stdin: bool,
|
|
112
|
+
},
|
|
113
|
+
/// Create or update an entry; the password is typed in a dialog
|
|
114
|
+
Add {
|
|
115
|
+
#[arg(long)]
|
|
116
|
+
name: String,
|
|
117
|
+
#[arg(long)]
|
|
118
|
+
username: Option<String>,
|
|
119
|
+
#[arg(long)]
|
|
120
|
+
uri: Option<String>,
|
|
121
|
+
#[arg(long)]
|
|
122
|
+
notes: Option<String>,
|
|
123
|
+
/// Read the password from stdin instead of a dialog
|
|
124
|
+
#[arg(long)]
|
|
125
|
+
password_stdin: bool,
|
|
126
|
+
/// Skip the "save this?" confirm window (the user already approved)
|
|
127
|
+
#[arg(long)]
|
|
128
|
+
yes: bool,
|
|
129
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
130
|
+
token: Option<String>,
|
|
131
|
+
},
|
|
132
|
+
/// Insert or update many entries from a JSON array on stdin (or --file)
|
|
133
|
+
Save {
|
|
134
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
135
|
+
token: Option<String>,
|
|
136
|
+
#[arg(long, value_name = "FILE")]
|
|
137
|
+
file: Option<PathBuf>,
|
|
138
|
+
/// The caller already approved this write in its own UI
|
|
139
|
+
#[arg(long)]
|
|
140
|
+
yes: bool,
|
|
141
|
+
},
|
|
142
|
+
/// Delete one entry
|
|
143
|
+
Remove {
|
|
144
|
+
name: String,
|
|
145
|
+
#[arg(long)]
|
|
146
|
+
yes: bool,
|
|
147
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
148
|
+
token: Option<String>,
|
|
149
|
+
},
|
|
150
|
+
/// Allow reads of one entry without a window for a while
|
|
151
|
+
Grant {
|
|
152
|
+
name: String,
|
|
153
|
+
#[arg(long, value_name = "MIN")]
|
|
154
|
+
minutes: Option<i64>,
|
|
155
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
156
|
+
token: Option<String>,
|
|
157
|
+
},
|
|
158
|
+
/// End grants for one entry, or all of them
|
|
159
|
+
Revoke {
|
|
160
|
+
name: Option<String>,
|
|
161
|
+
#[arg(long)]
|
|
162
|
+
all: bool,
|
|
163
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
164
|
+
token: Option<String>,
|
|
165
|
+
},
|
|
166
|
+
/// Recent audit lines (who asked for what)
|
|
167
|
+
Audit {
|
|
168
|
+
#[arg(default_value_t = 30)]
|
|
169
|
+
n: usize,
|
|
170
|
+
},
|
|
171
|
+
/// Import a Bitwarden JSON export (array or { items: [...] })
|
|
172
|
+
Import {
|
|
173
|
+
file: PathBuf,
|
|
174
|
+
#[arg(long)]
|
|
175
|
+
yes: bool,
|
|
176
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
177
|
+
token: Option<String>,
|
|
178
|
+
},
|
|
179
|
+
/// Diagnose paths, session directory and desktop availability
|
|
180
|
+
Doctor,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
#[derive(Debug)]
|
|
184
|
+
enum Fault {
|
|
185
|
+
Error(String),
|
|
186
|
+
Usage(String),
|
|
187
|
+
/// No desktop window could be opened; the host must supply the value.
|
|
188
|
+
NeedsUi(&'static str),
|
|
189
|
+
Denied(String),
|
|
190
|
+
Auth(String),
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
impl Fault {
|
|
194
|
+
fn exit_code(&self) -> i32 {
|
|
195
|
+
match self {
|
|
196
|
+
Fault::Error(_) => 1,
|
|
197
|
+
Fault::Usage(_) => 2,
|
|
198
|
+
Fault::NeedsUi(_) => 3,
|
|
199
|
+
Fault::Denied(_) => 4,
|
|
200
|
+
Fault::Auth(_) => 5,
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
impl From<String> for Fault {
|
|
206
|
+
fn from(message: String) -> Self {
|
|
207
|
+
Fault::Error(message)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
type Outcome = Result<(), Fault>;
|
|
212
|
+
|
|
213
|
+
pub fn run() -> i32 {
|
|
214
|
+
let cli = match Cli::try_parse() {
|
|
215
|
+
Ok(cli) => cli,
|
|
216
|
+
Err(e) => {
|
|
217
|
+
let _ = e.print();
|
|
218
|
+
return if e.use_stderr() { 2 } else { 0 };
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
let paths = Paths::resolve(cli.dir.clone());
|
|
222
|
+
migrate_legacy(&paths);
|
|
223
|
+
let json = cli.json;
|
|
224
|
+
match dispatch(cli.cmd, &paths, json) {
|
|
225
|
+
Ok(()) => 0,
|
|
226
|
+
Err(fault) => {
|
|
227
|
+
match &fault {
|
|
228
|
+
Fault::NeedsUi(step) => {
|
|
229
|
+
eprintln!("needs-ui: {step}");
|
|
230
|
+
eprintln!("no desktop window is available; the host must supply this value");
|
|
231
|
+
}
|
|
232
|
+
Fault::Usage(message) => eprintln!("ai-vault: {message}"),
|
|
233
|
+
Fault::Error(message) | Fault::Denied(message) | Fault::Auth(message) => {
|
|
234
|
+
eprintln!("ai-vault: {message}")
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
fault.exit_code()
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/// One-time move from the per-agent directory the TypeScript release used
|
|
243
|
+
/// (~/.omp/vault). The old file is copied, not removed: rolling back to that
|
|
244
|
+
/// extension still works.
|
|
245
|
+
fn migrate_legacy(paths: &Paths) {
|
|
246
|
+
// Only the real default directory: AI_VAULT_DIR is an explicit choice and
|
|
247
|
+
// must never inherit another location's store.
|
|
248
|
+
if paths.store().exists() || paths.dir != crate::paths::home().join(".ai-vault") {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
let legacy = crate::paths::home().join(".omp").join("vault");
|
|
252
|
+
let legacy_store = legacy.join("store.json");
|
|
253
|
+
if !legacy_store.exists() {
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if std::fs::create_dir_all(&paths.dir).is_err() {
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if std::fs::copy(&legacy_store, paths.store()).is_err() {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
let _ = std::fs::set_permissions(&paths.store(), std::fs::Permissions::from_mode(0o600));
|
|
263
|
+
if legacy.join("audit.log").exists() && !paths.audit().exists() {
|
|
264
|
+
let _ = std::fs::copy(legacy.join("audit.log"), paths.audit());
|
|
265
|
+
}
|
|
266
|
+
eprintln!(
|
|
267
|
+
"ai-vault: 已把共享库从 {} 复制到 {}(旧文件保留)",
|
|
268
|
+
legacy.display(),
|
|
269
|
+
paths.dir.display()
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
|
|
274
|
+
let out = Out { json };
|
|
275
|
+
match cmd {
|
|
276
|
+
Cmd::Path => {
|
|
277
|
+
out.json_value(json!({ "path": paths.store(), "dir": paths.dir, "sessions": paths.sessions() }));
|
|
278
|
+
out.text(paths.store().display().to_string());
|
|
279
|
+
Ok(())
|
|
280
|
+
}
|
|
281
|
+
Cmd::Doctor => doctor(paths, &out),
|
|
282
|
+
Cmd::Init { password_stdin, requester, idle_min } => {
|
|
283
|
+
init(paths, &out, password_stdin, &requester, idle_min)
|
|
284
|
+
}
|
|
285
|
+
Cmd::Unlock { password_stdin, requester, idle_min } => {
|
|
286
|
+
unlock(paths, &out, password_stdin, &requester, idle_min)
|
|
287
|
+
}
|
|
288
|
+
Cmd::Mode { action, value, hours, password_stdin } => {
|
|
289
|
+
mode(paths, &out, &action, value.as_deref(), hours, password_stdin)
|
|
290
|
+
}
|
|
291
|
+
Cmd::Status { token } => status(paths, &out, token),
|
|
292
|
+
Cmd::Lock { token, all } => lock(paths, &out, token, all),
|
|
293
|
+
Cmd::List { token } => list(paths, &out, token),
|
|
294
|
+
Cmd::Get { name, token, reason, answer_stdin } => {
|
|
295
|
+
get(paths, &out, token, &name, reason.as_deref(), answer_stdin)
|
|
296
|
+
}
|
|
297
|
+
Cmd::Add { name, username, uri, notes, password_stdin, yes, token } => {
|
|
298
|
+
add(paths, &out, token, AddRequest { name, username, uri, notes, password_stdin, yes })
|
|
299
|
+
}
|
|
300
|
+
Cmd::Save { token, file, yes } => save(paths, &out, token, file, yes),
|
|
301
|
+
Cmd::Remove { name, yes, token } => remove(paths, &out, token, &name, yes),
|
|
302
|
+
Cmd::Grant { name, minutes, token } => grant(paths, &out, token, &name, minutes),
|
|
303
|
+
Cmd::Revoke { name, all, token } => revoke(paths, &out, token, name.as_deref(), all),
|
|
304
|
+
Cmd::Audit { n } => audit_entries(paths, &out, n),
|
|
305
|
+
Cmd::Import { file, yes, token } => import_file(paths, &out, token, &file, yes),
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
struct Out {
|
|
310
|
+
json: bool,
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
impl Out {
|
|
314
|
+
fn json_value(&self, value: serde_json::Value) {
|
|
315
|
+
if self.json {
|
|
316
|
+
println!("{}", serde_json::to_string(&value).unwrap_or_else(|_| "{}".into()));
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
fn text(&self, text: impl AsRef<str>) {
|
|
321
|
+
if !self.json {
|
|
322
|
+
println!("{}", text.as_ref());
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
fn value(&self, value: serde_json::Value, human: impl FnOnce() -> String) {
|
|
327
|
+
if self.json {
|
|
328
|
+
self.json_value(value);
|
|
329
|
+
} else {
|
|
330
|
+
self.text(human());
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
fn idle_ms(minutes: Option<i64>) -> i64 {
|
|
336
|
+
minutes.map(|m| m.clamp(1, 600) * 60_000).unwrap_or(IDLE_MS_DEFAULT)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/// How long a token made now stays valid. `--idle-min` keeps the old
|
|
340
|
+
/// idle-based behaviour; otherwise the machine's mode decides:
|
|
341
|
+
/// never -> no deadline (and the token is stored machine-wide)
|
|
342
|
+
/// time -> absolute deadline, `hours` from now
|
|
343
|
+
/// session -> no deadline, with a 7-day ceiling in case an agent dies
|
|
344
|
+
/// without locking
|
|
345
|
+
fn policy(paths: &Paths, idle_min: Option<i64>) -> (i64, Option<i64>, UnlockPolicy) {
|
|
346
|
+
let policy = config::load(paths).unlock;
|
|
347
|
+
if let Some(minutes) = idle_min {
|
|
348
|
+
return (idle_ms(Some(minutes)), None, policy);
|
|
349
|
+
}
|
|
350
|
+
let now = session::now_ms();
|
|
351
|
+
match policy.mode {
|
|
352
|
+
UnlockMode::Never => (0, None, policy),
|
|
353
|
+
UnlockMode::Time => (0, Some(now + policy.hours.clamp(1, 24 * 90) * 3_600_000), policy),
|
|
354
|
+
UnlockMode::Session => (0, Some(now + 7 * 24 * 3_600_000), policy),
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// ---------------------------------------------------------------- input
|
|
359
|
+
|
|
360
|
+
fn read_password() -> Result<String, Fault> {
|
|
361
|
+
let line = read_line()?;
|
|
362
|
+
let password = line.trim_end_matches(['\r', '\n']).to_string();
|
|
363
|
+
if password.is_empty() {
|
|
364
|
+
return Err(Fault::Usage("empty password on stdin".into()));
|
|
365
|
+
}
|
|
366
|
+
Ok(password)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
fn read_line() -> Result<String, Fault> {
|
|
370
|
+
let mut line = String::new();
|
|
371
|
+
io::stdin()
|
|
372
|
+
.lock()
|
|
373
|
+
.read_line(&mut line)
|
|
374
|
+
.map_err(|e| Fault::Error(format!("cannot read stdin: {e}")))?;
|
|
375
|
+
Ok(line)
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
fn read_stdin_text() -> Result<String, Fault> {
|
|
379
|
+
let mut text = String::new();
|
|
380
|
+
io::stdin()
|
|
381
|
+
.read_to_string(&mut text)
|
|
382
|
+
.map_err(|e| Fault::Error(format!("cannot read stdin: {e}")))?;
|
|
383
|
+
Ok(text)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/// A yes/no answer from stdin, used when the host UI already asked the user.
|
|
387
|
+
fn read_approval() -> Result<bool, Fault> {
|
|
388
|
+
let answer = read_line()?.trim().to_lowercase();
|
|
389
|
+
Ok(matches!(answer.as_str(), "y" | "yes" | "allow" | "允许" | "1" | "true"))
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
fn ask_password(title: &str, label: &str) -> Result<String, Fault> {
|
|
393
|
+
match dialog::prompt_secret(title, label) {
|
|
394
|
+
Answer::Value(value) => Ok(value),
|
|
395
|
+
Answer::Cancelled => Err(Fault::Denied("cancelled: no password entered".into())),
|
|
396
|
+
Answer::NoUi => Err(Fault::NeedsUi("password")),
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
fn ask_text(title: &str, label: &str) -> Result<String, Fault> {
|
|
401
|
+
match dialog::prompt_text(title, label) {
|
|
402
|
+
Answer::Value(value) => Ok(value),
|
|
403
|
+
Answer::Cancelled => Err(Fault::Denied("cancelled".into())),
|
|
404
|
+
Answer::NoUi => Err(Fault::NeedsUi("text")),
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// ---------------------------------------------------------------- store access
|
|
409
|
+
|
|
410
|
+
fn open_store(paths: &Paths) -> Result<crypto::StoreFile, Fault> {
|
|
411
|
+
crypto::read_store(&paths.store())?.ok_or_else(|| {
|
|
412
|
+
Fault::Error(format!("vault is not initialized — run `ai-vault init` (store: {})", paths.store().display()))
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>, Fault> {
|
|
417
|
+
let key = session
|
|
418
|
+
.key()
|
|
419
|
+
.ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
|
|
420
|
+
crypto::open_with_key(store, &key).map_err(|e| match e {
|
|
421
|
+
crypto::OpenError::WrongPassword => Fault::Auth("the store does not open with this session — unlock again".into()),
|
|
422
|
+
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
423
|
+
})
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/// The auto session is the `never` mode token: no deadline, no password, and
|
|
427
|
+
/// it belongs to the machine rather than to one agent.
|
|
428
|
+
fn auto_session(paths: &Paths) -> Option<Session> {
|
|
429
|
+
let session = session::load_auto(paths).ok().flatten()?;
|
|
430
|
+
let store = crypto::read_store(&paths.store()).ok().flatten()?;
|
|
431
|
+
if crypto::store_id(&store) != session.store_id {
|
|
432
|
+
session::delete_auto(paths);
|
|
433
|
+
return None;
|
|
434
|
+
}
|
|
435
|
+
Some(session)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/// An explicit token, else the machine-wide auto session.
|
|
439
|
+
fn load_session(paths: &Paths, token: Option<&str>) -> Result<Session, Fault> {
|
|
440
|
+
if let Some(token) = token.filter(|t| !t.is_empty()) {
|
|
441
|
+
return session::load(paths, token).map_err(Fault::Auth);
|
|
442
|
+
}
|
|
443
|
+
auto_session(paths).ok_or_else(|| {
|
|
444
|
+
Fault::Auth("vault is locked (no session token) — unlock first".into())
|
|
445
|
+
})
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/// Write a session back where it came from: auto sessions stay machine-wide,
|
|
449
|
+
/// the others stay in the per-agent token file.
|
|
450
|
+
fn persist(paths: &Paths, session: &Session) {
|
|
451
|
+
let auto = session::load_auto(paths)
|
|
452
|
+
.ok()
|
|
453
|
+
.flatten()
|
|
454
|
+
.is_some_and(|saved| saved.token == session.token);
|
|
455
|
+
let _ = if auto { session::save_auto(paths, session) } else { session.save(paths) };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
fn touch(paths: &Paths, session: &mut Session) {
|
|
459
|
+
session.last_active = session::now_ms();
|
|
460
|
+
let _ = session.prune_grants(session.last_active);
|
|
461
|
+
persist(paths, session);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/// Read-modify-write under one advisory lock. The closure never opens a dialog
|
|
465
|
+
/// (that would block every other agent for minutes).
|
|
466
|
+
fn mutate<F>(paths: &Paths, session: &Session, f: F) -> Result<(), Fault>
|
|
467
|
+
where
|
|
468
|
+
F: FnOnce(&mut Vec<Item>, &str) -> Result<(), Fault>,
|
|
469
|
+
{
|
|
470
|
+
let _guard = StoreLock::acquire(paths)?;
|
|
471
|
+
let store = open_store(paths)?;
|
|
472
|
+
let mut items = items_with(session, &store)?;
|
|
473
|
+
let now = store::now_iso();
|
|
474
|
+
f(&mut items, &now)?;
|
|
475
|
+
let key = session
|
|
476
|
+
.key()
|
|
477
|
+
.ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
|
|
478
|
+
let salt = crypto::hex_to_bytes(&session.salt).ok_or_else(|| Fault::Error("session salt is corrupt".into()))?;
|
|
479
|
+
let sealed = crypto::seal(&salt, session.kdf.unwrap_or_default(), &key, &items)?;
|
|
480
|
+
let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
|
|
481
|
+
crypto::write_atomic(&paths.store(), &bytes)?;
|
|
482
|
+
Ok(())
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// ---------------------------------------------------------------- commands
|
|
486
|
+
|
|
487
|
+
fn doctor(paths: &Paths, out: &Out) -> Outcome {
|
|
488
|
+
session::ensure_session_dir(paths)?;
|
|
489
|
+
let value = json!({
|
|
490
|
+
"version": env!("CARGO_PKG_VERSION"),
|
|
491
|
+
"dir": paths.dir,
|
|
492
|
+
"store": paths.store(),
|
|
493
|
+
"initialized": paths.store().exists(),
|
|
494
|
+
"sessions": paths.sessions(),
|
|
495
|
+
"audit": paths.audit(),
|
|
496
|
+
"display": dialog::has_display(),
|
|
497
|
+
"zenity": which("zenity"),
|
|
498
|
+
"mode": config::load(paths).unlock.mode.as_str(),
|
|
499
|
+
"auto": paths.auto_session().exists(),
|
|
500
|
+
});
|
|
501
|
+
out.value(value.clone(), || {
|
|
502
|
+
let mut lines = Vec::new();
|
|
503
|
+
for (key, item) in value.as_object().into_iter().flatten() {
|
|
504
|
+
lines.push(format!("{key}: {}", item.as_str().map(str::to_string).unwrap_or_else(|| item.to_string())));
|
|
505
|
+
}
|
|
506
|
+
lines.join("\n")
|
|
507
|
+
});
|
|
508
|
+
Ok(())
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
fn which(program: &str) -> bool {
|
|
512
|
+
std::env::var_os("PATH").is_some_and(|paths| {
|
|
513
|
+
std::env::split_paths(&paths).any(|dir| dir.join(program).is_file())
|
|
514
|
+
})
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_min: Option<i64>) -> Outcome {
|
|
518
|
+
if paths.store().exists() {
|
|
519
|
+
return Err(Fault::Error(format!(
|
|
520
|
+
"vault already initialized — {}",
|
|
521
|
+
paths.store().display()
|
|
522
|
+
)));
|
|
523
|
+
}
|
|
524
|
+
let password = if password_stdin {
|
|
525
|
+
read_password()?
|
|
526
|
+
} else {
|
|
527
|
+
let first = ask_password("ai-vault · 创建主密码", "至少 8 位")?;
|
|
528
|
+
if first.len() < 8 {
|
|
529
|
+
return Err(Fault::Usage("the master password must be at least 8 characters".into()));
|
|
530
|
+
}
|
|
531
|
+
let again = ask_password("ai-vault · 确认主密码", "再输入一次")?;
|
|
532
|
+
if again != first {
|
|
533
|
+
return Err(Fault::Denied("the two passwords do not match".into()));
|
|
534
|
+
}
|
|
535
|
+
first
|
|
536
|
+
};
|
|
537
|
+
if password.len() < 8 {
|
|
538
|
+
return Err(Fault::Usage("the master password must be at least 8 characters".into()));
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
let salt = crypto::random_bytes::<16>();
|
|
542
|
+
let kdf = Kdf::default();
|
|
543
|
+
let key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
|
|
544
|
+
let sealed = crypto::seal(&salt, kdf, &key, &[])?;
|
|
545
|
+
{
|
|
546
|
+
let _guard = StoreLock::acquire(paths)?;
|
|
547
|
+
if paths.store().exists() {
|
|
548
|
+
return Err(Fault::Error("vault already initialized".into()));
|
|
549
|
+
}
|
|
550
|
+
let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
|
|
551
|
+
crypto::write_atomic(&paths.store(), &bytes)?;
|
|
552
|
+
}
|
|
553
|
+
session::ensure_session_dir(paths)?;
|
|
554
|
+
let (idle, deadline, policy) = policy(paths, idle_min);
|
|
555
|
+
let session = Session::new(requester, idle, deadline, &sealed, &key);
|
|
556
|
+
if policy.mode == UnlockMode::Never {
|
|
557
|
+
session::save_auto(paths, &session)?;
|
|
558
|
+
} else {
|
|
559
|
+
session.save(paths)?;
|
|
560
|
+
}
|
|
561
|
+
audit::append(&paths.audit(), requester, "init", None, None);
|
|
562
|
+
let value = json!({
|
|
563
|
+
"ok": true,
|
|
564
|
+
"path": paths.store(),
|
|
565
|
+
"token": session.token,
|
|
566
|
+
"expiresAt": session.expiry(),
|
|
567
|
+
"items": 0,
|
|
568
|
+
"mode": policy.mode.as_str(),
|
|
569
|
+
"auto": policy.mode == UnlockMode::Never,
|
|
570
|
+
});
|
|
571
|
+
out.value(value, || format!("created {}", paths.store().display()));
|
|
572
|
+
Ok(())
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_min: Option<i64>) -> Outcome {
|
|
576
|
+
let store = open_store(paths)?;
|
|
577
|
+
let password = if password_stdin {
|
|
578
|
+
read_password()?
|
|
579
|
+
} else {
|
|
580
|
+
ask_password("ai-vault · 解锁", "本地库主密码")?
|
|
581
|
+
};
|
|
582
|
+
let (items, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
583
|
+
crypto::OpenError::WrongPassword => {
|
|
584
|
+
audit::append(&paths.audit(), requester, "unlock_failed", None, Some("bad-password"));
|
|
585
|
+
Fault::Auth("wrong master password".into())
|
|
586
|
+
}
|
|
587
|
+
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
588
|
+
})?;
|
|
589
|
+
session::ensure_session_dir(paths)?;
|
|
590
|
+
session::sweep(paths);
|
|
591
|
+
let (idle, deadline, policy) = policy(paths, idle_min);
|
|
592
|
+
let session = Session::new(requester, idle, deadline, &store, &key);
|
|
593
|
+
if policy.mode == UnlockMode::Never {
|
|
594
|
+
session::save_auto(paths, &session)?;
|
|
595
|
+
} else {
|
|
596
|
+
session.save(paths)?;
|
|
597
|
+
}
|
|
598
|
+
audit::append(&paths.audit(), requester, "unlock", None, Some(policy.mode.as_str()));
|
|
599
|
+
let value = json!({
|
|
600
|
+
"ok": true,
|
|
601
|
+
"token": session.token,
|
|
602
|
+
"expiresAt": session.expiry(),
|
|
603
|
+
"items": items.len(),
|
|
604
|
+
"requester": requester,
|
|
605
|
+
"mode": policy.mode.as_str(),
|
|
606
|
+
"auto": policy.mode == UnlockMode::Never,
|
|
607
|
+
"path": paths.store(),
|
|
608
|
+
});
|
|
609
|
+
out.value(value, || format!("unlocked {} ({} entries)", paths.store().display(), items.len()));
|
|
610
|
+
Ok(())
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/// Show or change the password policy. Changing it always costs the master
|
|
614
|
+
/// password: `never` writes the key to disk, so it must not be a drive-by act.
|
|
615
|
+
fn mode(
|
|
616
|
+
paths: &Paths,
|
|
617
|
+
out: &Out,
|
|
618
|
+
action: &str,
|
|
619
|
+
value: Option<&str>,
|
|
620
|
+
hours: Option<i64>,
|
|
621
|
+
password_stdin: bool,
|
|
622
|
+
) -> Outcome {
|
|
623
|
+
match action.trim() {
|
|
624
|
+
"" | "get" | "status" => {
|
|
625
|
+
let policy = config::load(paths).unlock;
|
|
626
|
+
let auto = paths.auto_session().exists();
|
|
627
|
+
out.value(
|
|
628
|
+
json!({
|
|
629
|
+
"ok": true,
|
|
630
|
+
"mode": policy.mode.as_str(),
|
|
631
|
+
"hours": policy.hours,
|
|
632
|
+
"auto": auto,
|
|
633
|
+
"store": paths.store(),
|
|
634
|
+
}),
|
|
635
|
+
|| {
|
|
636
|
+
format!(
|
|
637
|
+
"mode: {}\nhours: {}\nmachine-wide session: {}",
|
|
638
|
+
policy.mode.as_str(),
|
|
639
|
+
policy.hours,
|
|
640
|
+
if auto { "yes (no password needed)" } else { "no" }
|
|
641
|
+
)
|
|
642
|
+
},
|
|
643
|
+
);
|
|
644
|
+
Ok(())
|
|
645
|
+
}
|
|
646
|
+
"set" => {
|
|
647
|
+
let value = value.ok_or_else(|| {
|
|
648
|
+
Fault::Usage("usage: ai-vault mode set never|time|session [--hours N]".into())
|
|
649
|
+
})?;
|
|
650
|
+
let mode = UnlockMode::parse(value)
|
|
651
|
+
.ok_or_else(|| Fault::Usage(format!("unknown mode \"{value}\" — use never, time or session")))?;
|
|
652
|
+
let store = open_store(paths)?;
|
|
653
|
+
let password = if password_stdin {
|
|
654
|
+
read_password()?
|
|
655
|
+
} else {
|
|
656
|
+
ask_password("ai-vault · 主密码", "切换解锁模式")?
|
|
657
|
+
};
|
|
658
|
+
let (_, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
659
|
+
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
660
|
+
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
661
|
+
})?;
|
|
662
|
+
let hours = hours.unwrap_or(config::load(paths).unlock.hours).clamp(1, 24 * 90);
|
|
663
|
+
config::save(paths, &config::Config { unlock: UnlockPolicy { mode, hours } })?;
|
|
664
|
+
session::ensure_session_dir(paths)?;
|
|
665
|
+
let auto = if mode == UnlockMode::Never {
|
|
666
|
+
let session = Session::new("mode", 0, None, &store, &key);
|
|
667
|
+
session::save_auto(paths, &session)?;
|
|
668
|
+
true
|
|
669
|
+
} else {
|
|
670
|
+
session::delete_auto(paths);
|
|
671
|
+
false
|
|
672
|
+
};
|
|
673
|
+
audit::append(&paths.audit(), "cli", "mode", None, Some(mode.as_str()));
|
|
674
|
+
let warn = if mode == UnlockMode::Never {
|
|
675
|
+
"\n注意: 密钥已写到磁盘(0600)。任何能读你文件的程序/人都能读出库里的密码。"
|
|
676
|
+
} else {
|
|
677
|
+
""
|
|
678
|
+
};
|
|
679
|
+
out.value(
|
|
680
|
+
json!({ "ok": true, "mode": mode.as_str(), "hours": hours, "auto": auto }),
|
|
681
|
+
|| {
|
|
682
|
+
format!(
|
|
683
|
+
"mode set to {}{}",
|
|
684
|
+
mode.as_str(),
|
|
685
|
+
if auto { " — no password needed from now on" } else { "" }
|
|
686
|
+
) + warn
|
|
687
|
+
},
|
|
688
|
+
);
|
|
689
|
+
Ok(())
|
|
690
|
+
}
|
|
691
|
+
other => Err(Fault::Usage(format!("unknown mode action \"{other}\""))),
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
fn status(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
|
|
696
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
697
|
+
let store = open_store(paths)?;
|
|
698
|
+
let items = items_with(&session, &store)?;
|
|
699
|
+
let now = session::now_ms();
|
|
700
|
+
session.prune_grants(now);
|
|
701
|
+
session.last_active = now;
|
|
702
|
+
persist(paths, &session);
|
|
703
|
+
let grants: serde_json::Map<String, serde_json::Value> = session
|
|
704
|
+
.grants
|
|
705
|
+
.iter()
|
|
706
|
+
.map(|(name, until)| (name.clone(), json!({ "expiresAt": until, "leftMs": until - now })))
|
|
707
|
+
.collect();
|
|
708
|
+
let policy = config::load(paths).unlock;
|
|
709
|
+
let auto = session::load_auto(paths)
|
|
710
|
+
.ok()
|
|
711
|
+
.flatten()
|
|
712
|
+
.is_some_and(|saved| saved.token == session.token);
|
|
713
|
+
let value = json!({
|
|
714
|
+
"ok": true,
|
|
715
|
+
"unlocked": true,
|
|
716
|
+
"items": items.len(),
|
|
717
|
+
"requester": session.requester,
|
|
718
|
+
"idleMs": session.idle_ms,
|
|
719
|
+
"expiresAt": session.expiry(),
|
|
720
|
+
"mode": policy.mode.as_str(),
|
|
721
|
+
"hours": policy.hours,
|
|
722
|
+
"auto": auto,
|
|
723
|
+
"store": paths.store(),
|
|
724
|
+
"grants": grants,
|
|
725
|
+
});
|
|
726
|
+
out.value(value.clone(), || {
|
|
727
|
+
let expiry = match session.expiry() {
|
|
728
|
+
Some(at) => format!("in {}s", ((at - now) / 1000).max(0)),
|
|
729
|
+
None => "never".to_string(),
|
|
730
|
+
};
|
|
731
|
+
let mut lines = vec![
|
|
732
|
+
format!("store: {}", paths.store().display()),
|
|
733
|
+
format!("requester: {}", session.requester),
|
|
734
|
+
"state: unlocked".to_string(),
|
|
735
|
+
format!("mode: {}{}", policy.mode.as_str(), if auto { " (machine-wide)" } else { "" }),
|
|
736
|
+
format!("items: {}", items.len()),
|
|
737
|
+
format!("expires: {expiry}"),
|
|
738
|
+
];
|
|
739
|
+
for (name, until) in &session.grants {
|
|
740
|
+
lines.push(format!("grant: {name} ({}s left)", ((until - now) / 1000).max(0)));
|
|
741
|
+
}
|
|
742
|
+
lines.join("\n")
|
|
743
|
+
});
|
|
744
|
+
Ok(())
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
fn lock(paths: &Paths, out: &Out, token: Option<String>, all: bool) -> Outcome {
|
|
748
|
+
let mut count = 0;
|
|
749
|
+
let mut auto = false;
|
|
750
|
+
if all {
|
|
751
|
+
count = session::delete_all(paths);
|
|
752
|
+
auto = session::delete_auto(paths);
|
|
753
|
+
} else if let Some(token) = token.filter(|t| !t.is_empty()) {
|
|
754
|
+
if session::delete(paths, &token) {
|
|
755
|
+
count = 1;
|
|
756
|
+
}
|
|
757
|
+
} else {
|
|
758
|
+
// No token: the only thing to lock here is the machine-wide session.
|
|
759
|
+
auto = session::delete_auto(paths);
|
|
760
|
+
if !auto {
|
|
761
|
+
return Err(Fault::Usage("pass --token or --all".into()));
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
if auto {
|
|
765
|
+
count += 1;
|
|
766
|
+
}
|
|
767
|
+
audit::append(&paths.audit(), "cli", "lock", None, Some(if all { "all" } else { "token" }));
|
|
768
|
+
out.value(json!({ "ok": true, "removed": count, "auto": auto }), || format!("locked {count} session(s)"));
|
|
769
|
+
Ok(())
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
fn list(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
|
|
773
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
774
|
+
let store = open_store(paths)?;
|
|
775
|
+
let items = items_with(&session, &store)?;
|
|
776
|
+
let summaries: Vec<ItemSummary> = items.iter().map(ItemSummary::from).collect();
|
|
777
|
+
touch(paths, &mut session);
|
|
778
|
+
audit::append(&paths.audit(), &session.requester, "list", None, None);
|
|
779
|
+
out.value(json!({ "ok": true, "count": summaries.len(), "items": summaries }), || {
|
|
780
|
+
if items.is_empty() {
|
|
781
|
+
return "(empty)".to_string();
|
|
782
|
+
}
|
|
783
|
+
items
|
|
784
|
+
.iter()
|
|
785
|
+
.map(|i| format!("{}\t{}\t{}", i.name, i.username.clone().unwrap_or_default(), i.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default()))
|
|
786
|
+
.collect::<Vec<_>>()
|
|
787
|
+
.join("\n")
|
|
788
|
+
});
|
|
789
|
+
Ok(())
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
fn get(
|
|
793
|
+
paths: &Paths,
|
|
794
|
+
out: &Out,
|
|
795
|
+
token: Option<String>,
|
|
796
|
+
name: &str,
|
|
797
|
+
reason: Option<&str>,
|
|
798
|
+
answer_stdin: bool,
|
|
799
|
+
) -> Outcome {
|
|
800
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
801
|
+
let store = open_store(paths)?;
|
|
802
|
+
let items = items_with(&session, &store)?;
|
|
803
|
+
let item = store::find(&items, name).cloned().ok_or_else(|| {
|
|
804
|
+
let names = items.iter().map(|i| i.name.clone()).collect::<Vec<_>>().join(", ");
|
|
805
|
+
Fault::Error(format!("no such entry: \"{name}\". available: {}", if names.is_empty() { "(empty)" } else { &names }))
|
|
806
|
+
})?;
|
|
807
|
+
|
|
808
|
+
let now = session::now_ms();
|
|
809
|
+
// `never` mode is the "the agent may use these freely" mode: the machine-wide
|
|
810
|
+
// session is the authorization, so no window opens on each read.
|
|
811
|
+
let auto = token.as_deref().map_or(true, |t| t.trim().is_empty());
|
|
812
|
+
let via = if auto {
|
|
813
|
+
"no-password"
|
|
814
|
+
} else if session.grant(&item.name, now).is_some() {
|
|
815
|
+
"existing-grant"
|
|
816
|
+
} else {
|
|
817
|
+
let message = format!(
|
|
818
|
+
"条目: {}\n请求方: {}\n原因: {}\n\n允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
|
|
819
|
+
item.name,
|
|
820
|
+
session.requester,
|
|
821
|
+
reason.unwrap_or("(未说明)")
|
|
822
|
+
);
|
|
823
|
+
let approved = if answer_stdin {
|
|
824
|
+
read_approval()?
|
|
825
|
+
} else {
|
|
826
|
+
match dialog::confirm("ai-vault · 读取本地密码", &message) {
|
|
827
|
+
Answer::Value(ok) => ok,
|
|
828
|
+
Answer::Cancelled => false,
|
|
829
|
+
Answer::NoUi => {
|
|
830
|
+
audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), Some("no-ui"));
|
|
831
|
+
return Err(Fault::NeedsUi("confirm"));
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
if !approved {
|
|
836
|
+
audit::append(&paths.audit(), &session.requester, "read_deny", Some(&item.name), reason);
|
|
837
|
+
return Err(Fault::Denied(format!("user denied access to \"{}\" — do not retry, ask the user instead", item.name)));
|
|
838
|
+
}
|
|
839
|
+
// The window may have outlived the idle lock or overlapped a write.
|
|
840
|
+
session = load_session(paths, token.as_deref())?;
|
|
841
|
+
let store = open_store(paths)?;
|
|
842
|
+
let items = items_with(&session, &store)?;
|
|
843
|
+
if store::find(&items, &item.name).is_none() {
|
|
844
|
+
return Err(Fault::Error(format!("\"{}\" was removed while the window was open", item.name)));
|
|
845
|
+
}
|
|
846
|
+
session.grants.insert(item.name.to_lowercase(), session::now_ms() + GRANT_MS_DEFAULT);
|
|
847
|
+
audit::append(&paths.audit(), &session.requester, "grant", Some(&item.name), Some("interactive"));
|
|
848
|
+
"interactive-grant"
|
|
849
|
+
};
|
|
850
|
+
|
|
851
|
+
session.last_active = session::now_ms();
|
|
852
|
+
persist(paths, &session);
|
|
853
|
+
audit::append(&paths.audit(), &session.requester, "read_allow", Some(&item.name), reason);
|
|
854
|
+
|
|
855
|
+
let mut value = serde_json::to_value(&item).map_err(|e| Fault::Error(e.to_string()))?;
|
|
856
|
+
if let Some(record) = value.as_object_mut() {
|
|
857
|
+
record.insert("via".into(), json!(via));
|
|
858
|
+
}
|
|
859
|
+
out.value(value.clone(), || serde_json::to_string_pretty(&value).unwrap_or_default());
|
|
860
|
+
Ok(())
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
struct AddRequest {
|
|
864
|
+
name: String,
|
|
865
|
+
username: Option<String>,
|
|
866
|
+
uri: Option<String>,
|
|
867
|
+
notes: Option<String>,
|
|
868
|
+
password_stdin: bool,
|
|
869
|
+
yes: bool,
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outcome {
|
|
873
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
874
|
+
let name = req.name.trim().to_string();
|
|
875
|
+
if name.is_empty() {
|
|
876
|
+
return Err(Fault::Usage("an entry needs a name".into()));
|
|
877
|
+
}
|
|
878
|
+
let store = open_store(paths)?;
|
|
879
|
+
let items = items_with(&session, &store)?;
|
|
880
|
+
let existing = store::find(&items, &name).cloned();
|
|
881
|
+
|
|
882
|
+
if !req.yes {
|
|
883
|
+
let mut meta = Vec::new();
|
|
884
|
+
if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
885
|
+
meta.push(format!("用户名: {user}"));
|
|
886
|
+
}
|
|
887
|
+
if let Some(uri) = req.uri.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
888
|
+
meta.push(format!("URI: {uri}"));
|
|
889
|
+
}
|
|
890
|
+
if let Some(notes) = req.notes.as_deref().map(str::trim).filter(|n| !n.is_empty()) {
|
|
891
|
+
meta.push(format!("备注: {notes}"));
|
|
892
|
+
}
|
|
893
|
+
let action = if existing.is_some() {
|
|
894
|
+
format!("更新已有条目「{name}」。")
|
|
895
|
+
} else {
|
|
896
|
+
format!("新建条目「{name}」。")
|
|
897
|
+
};
|
|
898
|
+
let message = format!(
|
|
899
|
+
"{action}{}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。",
|
|
900
|
+
if meta.is_empty() { String::new() } else { format!("\n{}", meta.join("\n")) }
|
|
901
|
+
);
|
|
902
|
+
match dialog::confirm("ai-vault · 保存到本地库", &message) {
|
|
903
|
+
Answer::Value(true) => {}
|
|
904
|
+
Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied(format!("user denied saving \"{name}\""))),
|
|
905
|
+
Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
let username = match req.username {
|
|
910
|
+
Some(user) => user,
|
|
911
|
+
None => {
|
|
912
|
+
let hint = if existing.as_ref().and_then(|i| i.username.as_ref()).is_some() {
|
|
913
|
+
"用户名(留空保持不变)"
|
|
914
|
+
} else {
|
|
915
|
+
"用户名(可留空)"
|
|
916
|
+
};
|
|
917
|
+
ask_text(&format!("ai-vault · {name}"), hint)?
|
|
918
|
+
}
|
|
919
|
+
};
|
|
920
|
+
let password = if req.password_stdin {
|
|
921
|
+
read_password()?
|
|
922
|
+
} else {
|
|
923
|
+
ask_password("ai-vault · 密码", &name)?
|
|
924
|
+
};
|
|
925
|
+
if password.is_empty() {
|
|
926
|
+
return Err(Fault::Denied("cancelled: no password entered".into()));
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
let user = username.trim().to_string();
|
|
930
|
+
let uri = req.uri.map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
|
|
931
|
+
let notes = req.notes.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
|
|
932
|
+
let draft = Draft {
|
|
933
|
+
id: None,
|
|
934
|
+
name: name.clone(),
|
|
935
|
+
username: if user.is_empty() { None } else { Some(user) },
|
|
936
|
+
password,
|
|
937
|
+
uris: uri.map(|u| vec![u]),
|
|
938
|
+
notes,
|
|
939
|
+
source: None,
|
|
940
|
+
};
|
|
941
|
+
let mut inserted = false;
|
|
942
|
+
mutate(paths, &session, |items, now| {
|
|
943
|
+
inserted = store::apply(items, draft, now);
|
|
944
|
+
Ok(())
|
|
945
|
+
})?;
|
|
946
|
+
session.last_active = session::now_ms();
|
|
947
|
+
persist(paths, &session);
|
|
948
|
+
audit::append(&paths.audit(), &session.requester, "add", Some(&name), None);
|
|
949
|
+
out.value(json!({ "ok": true, "item": name, "created": inserted }), || {
|
|
950
|
+
format!("saved \"{name}\" (password entered in the dialog, not shown)")
|
|
951
|
+
});
|
|
952
|
+
Ok(())
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
fn save(paths: &Paths, out: &Out, token: Option<String>, file: Option<PathBuf>, yes: bool) -> Outcome {
|
|
956
|
+
if !yes {
|
|
957
|
+
return Err(Fault::Usage("save needs --yes: the caller must confirm the write with the user".into()));
|
|
958
|
+
}
|
|
959
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
960
|
+
let text = match file {
|
|
961
|
+
Some(path) => std::fs::read_to_string(&path)
|
|
962
|
+
.map_err(|e| Fault::Error(format!("cannot read {}: {e}", path.display())))?,
|
|
963
|
+
None => read_stdin_text()?,
|
|
964
|
+
};
|
|
965
|
+
let drafts = import::parse_drafts(&text)?;
|
|
966
|
+
if drafts.is_empty() {
|
|
967
|
+
out.value(json!({ "ok": true, "count": 0, "names": [] }), || "nothing to save".to_string());
|
|
968
|
+
return Ok(());
|
|
969
|
+
}
|
|
970
|
+
let names: Vec<String> = drafts.iter().map(|d| d.name.clone()).collect();
|
|
971
|
+
let mut count = 0;
|
|
972
|
+
mutate(paths, &session, |items, now| {
|
|
973
|
+
for draft in drafts {
|
|
974
|
+
store::apply(items, draft, now);
|
|
975
|
+
count += 1;
|
|
976
|
+
}
|
|
977
|
+
Ok(())
|
|
978
|
+
})?;
|
|
979
|
+
session.last_active = session::now_ms();
|
|
980
|
+
persist(paths, &session);
|
|
981
|
+
audit::append(&paths.audit(), &session.requester, "import", Some(&format!("drafts:{count}")), None);
|
|
982
|
+
out.value(json!({ "ok": true, "count": count, "names": names }), || format!("saved {count} entries"));
|
|
983
|
+
Ok(())
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
fn remove(paths: &Paths, out: &Out, token: Option<String>, name: &str, yes: bool) -> Outcome {
|
|
987
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
988
|
+
let store = open_store(paths)?;
|
|
989
|
+
let items = items_with(&session, &store)?;
|
|
990
|
+
if store::find(&items, name).is_none() {
|
|
991
|
+
return Err(Fault::Error(format!("no such entry: \"{name}\"")));
|
|
992
|
+
}
|
|
993
|
+
if !yes {
|
|
994
|
+
match dialog::confirm("ai-vault · 删除条目", &format!("删除「{name}」?删除后无法恢复。")) {
|
|
995
|
+
Answer::Value(true) => {}
|
|
996
|
+
Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
|
|
997
|
+
Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
let mut removed = false;
|
|
1001
|
+
mutate(paths, &session, |items, _now| {
|
|
1002
|
+
removed = store::remove(items, name);
|
|
1003
|
+
Ok(())
|
|
1004
|
+
})?;
|
|
1005
|
+
session.grants.remove(&name.to_lowercase());
|
|
1006
|
+
session.last_active = session::now_ms();
|
|
1007
|
+
persist(paths, &session);
|
|
1008
|
+
audit::append(&paths.audit(), &session.requester, "remove", Some(name), None);
|
|
1009
|
+
out.value(json!({ "ok": true, "removed": removed }), || if removed { "removed".to_string() } else { "not found".to_string() });
|
|
1010
|
+
Ok(())
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
fn grant(paths: &Paths, out: &Out, token: Option<String>, name: &str, minutes: Option<i64>) -> Outcome {
|
|
1014
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
1015
|
+
let store = open_store(paths)?;
|
|
1016
|
+
let items = items_with(&session, &store)?;
|
|
1017
|
+
let item = store::find(&items, name).ok_or_else(|| Fault::Error(format!("no such entry: \"{name}\"")))?;
|
|
1018
|
+
let minutes = minutes.unwrap_or(GRANT_MS_DEFAULT / 60_000).clamp(1, GRANT_MS_MAX / 60_000);
|
|
1019
|
+
let until = session::now_ms() + minutes * 60_000;
|
|
1020
|
+
session.grants.insert(item.name.to_lowercase(), until);
|
|
1021
|
+
session.last_active = session::now_ms();
|
|
1022
|
+
persist(paths, &session);
|
|
1023
|
+
audit::append(&paths.audit(), &session.requester, "grant", Some(&item.name), Some("manual"));
|
|
1024
|
+
out.value(json!({ "ok": true, "name": item.name, "minutes": minutes, "expiresAt": until }), || {
|
|
1025
|
+
format!("granted \"{}\" for {minutes}m", item.name)
|
|
1026
|
+
});
|
|
1027
|
+
Ok(())
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
fn revoke(paths: &Paths, out: &Out, token: Option<String>, name: Option<&str>, all: bool) -> Outcome {
|
|
1031
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
1032
|
+
if all {
|
|
1033
|
+
session.grants.clear();
|
|
1034
|
+
} else if let Some(name) = name.filter(|n| !n.is_empty()) {
|
|
1035
|
+
session.grants.remove(&name.to_lowercase());
|
|
1036
|
+
} else {
|
|
1037
|
+
return Err(Fault::Usage("pass an entry name or --all".into()));
|
|
1038
|
+
}
|
|
1039
|
+
session.last_active = session::now_ms();
|
|
1040
|
+
persist(paths, &session);
|
|
1041
|
+
audit::append(&paths.audit(), &session.requester, "revoke", name, Some(if all { "all" } else { "entry" }));
|
|
1042
|
+
out.value(json!({ "ok": true }), || "revoked".to_string());
|
|
1043
|
+
Ok(())
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
fn audit_entries(paths: &Paths, out: &Out, n: usize) -> Outcome {
|
|
1047
|
+
let limit = n.clamp(1, 1000);
|
|
1048
|
+
let entries = audit::read(&paths.audit(), limit);
|
|
1049
|
+
out.value(json!({ "ok": true, "entries": entries }), || {
|
|
1050
|
+
entries
|
|
1051
|
+
.iter()
|
|
1052
|
+
.map(|e| {
|
|
1053
|
+
format!(
|
|
1054
|
+
"{} {} {}{}{}",
|
|
1055
|
+
e.ts,
|
|
1056
|
+
e.session,
|
|
1057
|
+
e.event,
|
|
1058
|
+
e.item.as_ref().map(|i| format!(" {i}")).unwrap_or_default(),
|
|
1059
|
+
e.reason.as_ref().map(|r| format!(" ({r})")).unwrap_or_default()
|
|
1060
|
+
)
|
|
1061
|
+
})
|
|
1062
|
+
.collect::<Vec<_>>()
|
|
1063
|
+
.join("\n")
|
|
1064
|
+
});
|
|
1065
|
+
Ok(())
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
fn import_file(paths: &Paths, out: &Out, token: Option<String>, file: &PathBuf, yes: bool) -> Outcome {
|
|
1069
|
+
let mut session = load_session(paths, token.as_deref())?;
|
|
1070
|
+
let text = std::fs::read_to_string(file)
|
|
1071
|
+
.map_err(|e| Fault::Error(format!("cannot read {}: {e}", file.display())))?;
|
|
1072
|
+
let drafts = import::parse_bitwarden_json(&text)?;
|
|
1073
|
+
if drafts.is_empty() {
|
|
1074
|
+
return Err(Fault::Error("no login items with a password in that export".into()));
|
|
1075
|
+
}
|
|
1076
|
+
if !yes {
|
|
1077
|
+
let shown = drafts
|
|
1078
|
+
.iter()
|
|
1079
|
+
.take(15)
|
|
1080
|
+
.map(|d| format!("• {}{}", d.name, d.username.as_ref().map(|u| format!(" user:{u}")).unwrap_or_default()))
|
|
1081
|
+
.collect::<Vec<_>>()
|
|
1082
|
+
.join("\n");
|
|
1083
|
+
let more = if drafts.len() > 15 { format!("\n… 还有 {} 条", drafts.len() - 15) } else { String::new() };
|
|
1084
|
+
let message = format!(
|
|
1085
|
+
"匹配 {} 条。其中带密码的登录项会写入本地加密库,同名条目会被更新。\n\n{shown}{more}\n\n允许导入?",
|
|
1086
|
+
drafts.len()
|
|
1087
|
+
);
|
|
1088
|
+
match dialog::confirm("ai-vault · 从 Bitwarden 导入", &message) {
|
|
1089
|
+
Answer::Value(true) => {}
|
|
1090
|
+
Answer::Value(false) | Answer::Cancelled => return Err(Fault::Denied("user denied the Bitwarden import".into())),
|
|
1091
|
+
Answer::NoUi => return Err(Fault::NeedsUi("confirm")),
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
let names: Vec<String> = drafts.iter().map(|d| d.name.clone()).collect();
|
|
1095
|
+
let mut count = 0;
|
|
1096
|
+
mutate(paths, &session, |items, now| {
|
|
1097
|
+
for draft in drafts {
|
|
1098
|
+
store::apply(items, draft, now);
|
|
1099
|
+
count += 1;
|
|
1100
|
+
}
|
|
1101
|
+
Ok(())
|
|
1102
|
+
})?;
|
|
1103
|
+
session.last_active = session::now_ms();
|
|
1104
|
+
persist(paths, &session);
|
|
1105
|
+
audit::append(&paths.audit(), &session.requester, "import", Some(&format!("json:{count}")), None);
|
|
1106
|
+
out.value(json!({ "ok": true, "count": count, "names": names }), || format!("imported {count} login items"));
|
|
1107
|
+
Ok(())
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
#[cfg(test)]
|
|
1111
|
+
mod tests {
|
|
1112
|
+
use super::*;
|
|
1113
|
+
|
|
1114
|
+
#[test]
|
|
1115
|
+
fn exit_codes_are_stable() {
|
|
1116
|
+
assert_eq!(Fault::Error("x".into()).exit_code(), 1);
|
|
1117
|
+
assert_eq!(Fault::Usage("x".into()).exit_code(), 2);
|
|
1118
|
+
assert_eq!(Fault::NeedsUi("password").exit_code(), 3);
|
|
1119
|
+
assert_eq!(Fault::Denied("x".into()).exit_code(), 4);
|
|
1120
|
+
assert_eq!(Fault::Auth("x".into()).exit_code(), 5);
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
#[test]
|
|
1124
|
+
fn idle_is_clamped() {
|
|
1125
|
+
assert_eq!(idle_ms(None), IDLE_MS_DEFAULT);
|
|
1126
|
+
assert_eq!(idle_ms(Some(0)), 60_000);
|
|
1127
|
+
assert_eq!(idle_ms(Some(1000)), 600 * 60_000);
|
|
1128
|
+
}
|
|
1129
|
+
}
|