@xiaolikt/ai-vault 0.10.0 → 0.12.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 +1 -1
- package/README.md +45 -7
- package/README.zh.md +34 -5
- package/crates/ai-vault/Cargo.toml +1 -1
- package/crates/ai-vault/src/cli.rs +441 -119
- package/crates/ai-vault/src/config.rs +41 -12
- package/crates/ai-vault/src/crypto.rs +69 -18
- package/crates/ai-vault/src/import.rs +85 -48
- package/crates/ai-vault/src/sealed.rs +1 -9
- package/crates/ai-vault/src/session.rs +79 -22
- package/crates/ai-vault/src/store.rs +237 -5
- package/package.json +4 -4
- package/packages/pi-ai-vault/README.md +1 -1
- package/packages/pi-ai-vault/README.zh.md +1 -1
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +42 -26
- package/packages/pi-ai-vault/src/cli.ts +9 -3
- package/packages/pi-ai-vault/src/import-map.ts +166 -58
- package/packages/pi-ai-vault/src/index.ts +172 -48
- package/packages/pi-ai-vault/src/settings.ts +37 -7
- package/packages/pi-ai-vault/src/types.ts +52 -0
- package/test/cli.sh +112 -24
- package/tests/bitwarden-tools.test.mjs +2 -2
- package/tests/ente.test.mjs +25 -6
- package/tests/helpers.mjs +36 -0
- package/tests/import-map.test.mjs +75 -38
- package/tests/mocks/bin/bw +5 -1
- package/tests/vault-cli.test.mjs +77 -19
|
@@ -16,7 +16,7 @@ use crate::i18n::{tr, tr_owned};
|
|
|
16
16
|
use crate::import;
|
|
17
17
|
use crate::paths::{Paths, GRANT_MS_DEFAULT, GRANT_MS_MAX, IDLE_MS_DEFAULT};
|
|
18
18
|
use crate::session::{self, Session, StoreLock};
|
|
19
|
-
use crate::store::{
|
|
19
|
+
use crate::store::{Draft, Item, ItemType, self};
|
|
20
20
|
use crate::{audit, store::ItemSummary};
|
|
21
21
|
|
|
22
22
|
#[derive(Parser, Debug)]
|
|
@@ -70,24 +70,32 @@ enum Cmd {
|
|
|
70
70
|
},
|
|
71
71
|
/// Show or change machine-wide settings
|
|
72
72
|
Settings {
|
|
73
|
-
/// Dotted key (vault.unlock, vault.hours,
|
|
74
|
-
/// bitwarden.hours, bitwarden.import); omit
|
|
73
|
+
/// Dotted key (vault.unlock, vault.hours, vault.confirm,
|
|
74
|
+
/// bitwarden.unlock, bitwarden.hours, bitwarden.import, ente.*); omit
|
|
75
|
+
/// to print everything
|
|
75
76
|
key: Option<String>,
|
|
76
77
|
/// New value; omit to print the current one
|
|
77
78
|
value: Option<String>,
|
|
78
|
-
/// Read the vault master password from stdin (
|
|
79
|
+
/// Read the vault master password from stdin (for the changes that need it)
|
|
79
80
|
#[arg(long)]
|
|
80
81
|
password_stdin: bool,
|
|
82
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
83
|
+
token: Option<String>,
|
|
81
84
|
},
|
|
82
85
|
/// The persisted `bw` session key (bitwarden.unlock = never | time)
|
|
83
86
|
BwSession {
|
|
84
87
|
/// get | put | clear
|
|
85
88
|
action: String,
|
|
89
|
+
/// `put` reads the policy from the store, so it needs an unlocked session
|
|
90
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
91
|
+
token: Option<String>,
|
|
86
92
|
},
|
|
87
93
|
/// Ente's `ENTE_CLI_VAULT_KEY` (ente.unlock = never | time)
|
|
88
94
|
EnteSession {
|
|
89
95
|
/// get | put | clear
|
|
90
96
|
action: String,
|
|
97
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
98
|
+
token: Option<String>,
|
|
91
99
|
},
|
|
92
100
|
/// Show or change how often the master password is asked for
|
|
93
101
|
Mode {
|
|
@@ -102,6 +110,8 @@ enum Cmd {
|
|
|
102
110
|
/// Read the master password from stdin (changing the mode needs it)
|
|
103
111
|
#[arg(long)]
|
|
104
112
|
password_stdin: bool,
|
|
113
|
+
#[arg(long, env = "AI_VAULT_TOKEN")]
|
|
114
|
+
token: Option<String>,
|
|
105
115
|
},
|
|
106
116
|
/// Session state, item count, and remaining read grants
|
|
107
117
|
Status {
|
|
@@ -137,17 +147,29 @@ enum Cmd {
|
|
|
137
147
|
#[arg(long, value_name = "HEX")]
|
|
138
148
|
approval: Option<String>,
|
|
139
149
|
},
|
|
140
|
-
/// Create or update an entry; the
|
|
150
|
+
/// Create or update an entry of any type; the secret is typed in a dialog
|
|
141
151
|
Add {
|
|
142
152
|
#[arg(long)]
|
|
143
153
|
name: String,
|
|
154
|
+
/// login (default) | note | card | identity | sshkey | bankaccount | driverslicense | passport
|
|
155
|
+
#[arg(long, value_name = "TYPE")]
|
|
156
|
+
r#type: Option<String>,
|
|
144
157
|
#[arg(long)]
|
|
145
158
|
username: Option<String>,
|
|
146
159
|
#[arg(long)]
|
|
147
160
|
uri: Option<String>,
|
|
148
161
|
#[arg(long)]
|
|
149
162
|
notes: Option<String>,
|
|
150
|
-
///
|
|
163
|
+
/// A field of the type, NAME=VALUE; repeatable. A field given as NAME
|
|
164
|
+
/// alone, or any hidden field left out, is typed in a dialog (or sent
|
|
165
|
+
/// on stdin for the primary one with --password-stdin).
|
|
166
|
+
#[arg(long = "field", value_name = "NAME[=VALUE]")]
|
|
167
|
+
fields: Vec<String>,
|
|
168
|
+
/// A hidden field supplied by a host that already asked the user for
|
|
169
|
+
/// it, NAME=VALUE; repeatable. Never printed, never in a window.
|
|
170
|
+
#[arg(long = "secret", value_name = "NAME=VALUE")]
|
|
171
|
+
secrets: Vec<String>,
|
|
172
|
+
/// Read the secret from stdin instead of a dialog
|
|
151
173
|
#[arg(long)]
|
|
152
174
|
password_stdin: bool,
|
|
153
175
|
/// Skip the "save this?" confirm window (the user already approved)
|
|
@@ -218,6 +240,8 @@ enum Fault {
|
|
|
218
240
|
Usage(String),
|
|
219
241
|
/// No desktop window could be opened; the host must supply the value.
|
|
220
242
|
NeedsUi(&'static str),
|
|
243
|
+
/// The same, for one named hidden field of a typed entry.
|
|
244
|
+
NeedsUiField(String),
|
|
221
245
|
Denied(String),
|
|
222
246
|
Auth(String),
|
|
223
247
|
}
|
|
@@ -227,7 +251,7 @@ impl Fault {
|
|
|
227
251
|
match self {
|
|
228
252
|
Fault::Error(_) => 1,
|
|
229
253
|
Fault::Usage(_) => 2,
|
|
230
|
-
Fault::NeedsUi(_) => 3,
|
|
254
|
+
Fault::NeedsUi(_) | Fault::NeedsUiField(_) => 3,
|
|
231
255
|
Fault::Denied(_) => 4,
|
|
232
256
|
Fault::Auth(_) => 5,
|
|
233
257
|
}
|
|
@@ -266,6 +290,11 @@ pub fn run() -> i32 {
|
|
|
266
290
|
eprintln!("needs-ui: {step}");
|
|
267
291
|
eprintln!("no desktop window is available; the host must supply this value");
|
|
268
292
|
}
|
|
293
|
+
Fault::NeedsUiField(field) => {
|
|
294
|
+
eprintln!("needs-ui: password field={field}");
|
|
295
|
+
eprintln!("no desktop window is available; the host must supply this value");
|
|
296
|
+
}
|
|
297
|
+
// (NeedsUi with a detail is printed by `needs_ui` below)
|
|
269
298
|
Fault::Usage(message) => eprintln!("ai-vault: {message}"),
|
|
270
299
|
Fault::Error(message) | Fault::Denied(message) | Fault::Auth(message) => {
|
|
271
300
|
eprintln!("ai-vault: {message}")
|
|
@@ -323,13 +352,13 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
|
|
|
323
352
|
Cmd::Unlock { password_stdin, requester, idle_min } => {
|
|
324
353
|
unlock(paths, &out, password_stdin, &requester, idle_min)
|
|
325
354
|
}
|
|
326
|
-
Cmd::Settings { key, value, password_stdin } => {
|
|
327
|
-
settings(paths, &out, key.as_deref(), value.as_deref(), None, password_stdin)
|
|
355
|
+
Cmd::Settings { key, value, password_stdin, token } => {
|
|
356
|
+
settings(paths, &out, token.as_deref(), key.as_deref(), value.as_deref(), None, password_stdin)
|
|
328
357
|
}
|
|
329
|
-
Cmd::BwSession { action } => sealed_session(paths, &out, Kind::Bitwarden, &action),
|
|
330
|
-
Cmd::EnteSession { action } => sealed_session(paths, &out, Kind::Ente, &action),
|
|
331
|
-
Cmd::Mode { action, value, hours, password_stdin } => {
|
|
332
|
-
mode(paths, &out, &action, value.as_deref(), hours, password_stdin)
|
|
358
|
+
Cmd::BwSession { action, token } => sealed_session(paths, &out, Kind::Bitwarden, &action, token.as_deref()),
|
|
359
|
+
Cmd::EnteSession { action, token } => sealed_session(paths, &out, Kind::Ente, &action, token.as_deref()),
|
|
360
|
+
Cmd::Mode { action, value, hours, password_stdin, token } => {
|
|
361
|
+
mode(paths, &out, token.as_deref(), &action, value.as_deref(), hours, password_stdin)
|
|
333
362
|
}
|
|
334
363
|
Cmd::Status { token } => status(paths, &out, token),
|
|
335
364
|
Cmd::Lock { token, all } => lock(paths, &out, token, all),
|
|
@@ -337,8 +366,8 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
|
|
|
337
366
|
Cmd::Get { name, token, reason, answer_stdin, approval } => {
|
|
338
367
|
get(paths, &out, token, &name, reason.as_deref(), answer_stdin, approval)
|
|
339
368
|
}
|
|
340
|
-
Cmd::Add { name, username, uri, notes, password_stdin, yes, token } => {
|
|
341
|
-
add(paths, &out, token, AddRequest { name, username, uri, notes, password_stdin, yes })
|
|
369
|
+
Cmd::Add { name, r#type, username, uri, notes, fields, secrets, password_stdin, yes, token } => {
|
|
370
|
+
add(paths, &out, token, AddRequest { name, r#type, username, uri, notes, fields, secrets, password_stdin, yes })
|
|
342
371
|
}
|
|
343
372
|
Cmd::Save { token, file, yes } => save(paths, &out, token, file, yes),
|
|
344
373
|
Cmd::Remove { name, yes, token } => remove(paths, &out, token, &name, yes),
|
|
@@ -385,8 +414,8 @@ fn idle_ms(minutes: Option<i64>) -> i64 {
|
|
|
385
414
|
/// time -> absolute deadline, `hours` from now
|
|
386
415
|
/// session -> no deadline, with a 7-day ceiling in case an agent dies
|
|
387
416
|
/// without locking
|
|
388
|
-
fn policy(
|
|
389
|
-
let policy = config
|
|
417
|
+
fn policy(idle_min: Option<i64>, config: &config::Config) -> (i64, Option<i64>, UnlockPolicy) {
|
|
418
|
+
let policy = config.unlock;
|
|
390
419
|
if let Some(minutes) = idle_min {
|
|
391
420
|
return (idle_ms(Some(minutes)), None, policy);
|
|
392
421
|
}
|
|
@@ -455,11 +484,17 @@ fn ask_password(title: &str, label: &str) -> Result<String, Fault> {
|
|
|
455
484
|
}
|
|
456
485
|
}
|
|
457
486
|
|
|
458
|
-
|
|
459
|
-
|
|
487
|
+
/// The same, naming the field on the `needs-ui` line so a host can title its
|
|
488
|
+
/// own dialog and send the value back as `--secret NAME=VALUE`.
|
|
489
|
+
/// The same, but when no window can open the `needs-ui` line names the field,
|
|
490
|
+
/// so a host can title its own dialog and send the answer back as `--secret`.
|
|
491
|
+
/// The field is reported in the error's text, which the host reads after the
|
|
492
|
+
/// `needs-ui: password` line.
|
|
493
|
+
fn ask_field_password(field: &str, title: &str, label: &str) -> Result<String, Fault> {
|
|
494
|
+
match dialog::prompt_secret(title, label) {
|
|
460
495
|
Answer::Value(value) => Ok(value),
|
|
461
|
-
Answer::Cancelled => Err(Fault::Denied("cancelled".into())),
|
|
462
|
-
Answer::NoUi => Err(Fault::
|
|
496
|
+
Answer::Cancelled => Err(Fault::Denied("cancelled: no password entered".into())),
|
|
497
|
+
Answer::NoUi => Err(Fault::NeedsUiField(field.to_string())),
|
|
463
498
|
}
|
|
464
499
|
}
|
|
465
500
|
|
|
@@ -472,6 +507,10 @@ fn open_store(paths: &Paths) -> Result<crypto::StoreFile, Fault> {
|
|
|
472
507
|
}
|
|
473
508
|
|
|
474
509
|
fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>, Fault> {
|
|
510
|
+
Ok(payload_with(session, store)?.items)
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
fn payload_with(session: &Session, store: &crypto::StoreFile) -> Result<crypto::Payload, Fault> {
|
|
475
514
|
let key = session
|
|
476
515
|
.key()
|
|
477
516
|
.ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
|
|
@@ -481,6 +520,19 @@ fn items_with(session: &Session, store: &crypto::StoreFile) -> Result<Vec<Item>,
|
|
|
481
520
|
})
|
|
482
521
|
}
|
|
483
522
|
|
|
523
|
+
/// Write the settings back into the store under this session's key.
|
|
524
|
+
fn config_write(paths: &Paths, session: &Session, config: &config::Config) -> Result<(), Fault> {
|
|
525
|
+
let _guard = StoreLock::acquire(paths)?;
|
|
526
|
+
let store = open_store(paths)?;
|
|
527
|
+
let key = session
|
|
528
|
+
.key()
|
|
529
|
+
.ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
|
|
530
|
+
let sealed = config::write_with(&store, &key, config)?;
|
|
531
|
+
let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
|
|
532
|
+
crypto::write_atomic(&paths.store(), &bytes)?;
|
|
533
|
+
Ok(())
|
|
534
|
+
}
|
|
535
|
+
|
|
484
536
|
/// The secret the host process (pi/omp extension) holds and passes to each
|
|
485
537
|
/// CLI call through the environment. A bare `ai-vault` typed by a human has
|
|
486
538
|
/// none, which is fine: that caller never needs to relay an approval.
|
|
@@ -488,13 +540,18 @@ fn host_secret() -> Option<String> {
|
|
|
488
540
|
std::env::var("AI_VAULT_HOST_SECRET").ok().filter(|s| !s.is_empty())
|
|
489
541
|
}
|
|
490
542
|
|
|
491
|
-
/// What session
|
|
492
|
-
///
|
|
493
|
-
fn
|
|
494
|
-
|
|
495
|
-
|
|
543
|
+
/// What a session file is signed with: the host's memory-only secret when
|
|
544
|
+
/// the caller presented one, else the store's wrap key (a human at a terminal).
|
|
545
|
+
fn signer(paths: &Paths) -> Result<session::Signer, String> {
|
|
546
|
+
match host_secret() {
|
|
547
|
+
Some(secret) => Ok(session::Signer::Host(secret)),
|
|
548
|
+
None => sealed::wrap_key_hex(paths).map(session::Signer::Wrap),
|
|
496
549
|
}
|
|
497
|
-
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/// Both keys, for checking a file against whichever one signed it.
|
|
553
|
+
fn signing_keys(paths: &Paths) -> Result<(Option<String>, Option<String>), String> {
|
|
554
|
+
Ok((host_secret(), Some(sealed::wrap_key_hex(paths)?)))
|
|
498
555
|
}
|
|
499
556
|
|
|
500
557
|
/// The host integration (the extension) is recognised by the secret it
|
|
@@ -502,7 +559,7 @@ fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
|
|
|
502
559
|
/// and is treated like a human caller until it has a secret to sign with.
|
|
503
560
|
/// This keeps a half-configured host from getting a session it can neither
|
|
504
561
|
/// verify nor relay for.
|
|
505
|
-
fn
|
|
562
|
+
fn secret_kind_label(kind: Kind) -> &'static str {
|
|
506
563
|
match kind {
|
|
507
564
|
Kind::Bitwarden => "bitwarden",
|
|
508
565
|
Kind::Ente => "ente",
|
|
@@ -528,7 +585,8 @@ fn auto_session(paths: &Paths) -> Option<Session> {
|
|
|
528
585
|
/// An explicit token, else the machine-wide auto session.
|
|
529
586
|
fn load_session(paths: &Paths, token: Option<&str>) -> Result<Session, Fault> {
|
|
530
587
|
if let Some(token) = token.filter(|t| !t.is_empty()) {
|
|
531
|
-
|
|
588
|
+
let (host, wrap) = signing_keys(paths)?;
|
|
589
|
+
return session::load(paths, token, host.as_deref(), wrap.as_deref()).map_err(Fault::Auth);
|
|
532
590
|
}
|
|
533
591
|
auto_session(paths).ok_or_else(|| {
|
|
534
592
|
Fault::Auth("vault is locked (no session token) — unlock first".into())
|
|
@@ -547,8 +605,8 @@ fn persist(paths: &Paths, session: &Session) {
|
|
|
547
605
|
} else {
|
|
548
606
|
// Best-effort like the rest of this helper; a failed sign means the
|
|
549
607
|
// next call simply asks to unlock again.
|
|
550
|
-
match
|
|
551
|
-
Ok(
|
|
608
|
+
match signer(paths) {
|
|
609
|
+
Ok(signer) => session.save(paths, &signer),
|
|
552
610
|
Err(e) => Err(e),
|
|
553
611
|
}
|
|
554
612
|
};
|
|
@@ -568,14 +626,14 @@ where
|
|
|
568
626
|
{
|
|
569
627
|
let _guard = StoreLock::acquire(paths)?;
|
|
570
628
|
let store = open_store(paths)?;
|
|
571
|
-
let mut
|
|
629
|
+
let mut payload = payload_with(session, &store)?;
|
|
572
630
|
let now = store::now_iso();
|
|
573
|
-
f(&mut items, &now)?;
|
|
631
|
+
f(&mut payload.items, &now)?;
|
|
574
632
|
let key = session
|
|
575
633
|
.key()
|
|
576
634
|
.ok_or_else(|| Fault::Auth("session token has no usable key — unlock again".into()))?;
|
|
577
635
|
let salt = crypto::hex_to_bytes(&session.salt).ok_or_else(|| Fault::Error("session salt is corrupt".into()))?;
|
|
578
|
-
let sealed = crypto::seal(&salt, session.kdf.unwrap_or_default(), &key, &items)?;
|
|
636
|
+
let sealed = crypto::seal(&salt, session.kdf.unwrap_or_default(), &key, &payload.items, &payload.config)?;
|
|
579
637
|
let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
|
|
580
638
|
crypto::write_atomic(&paths.store(), &bytes)?;
|
|
581
639
|
Ok(())
|
|
@@ -593,14 +651,14 @@ fn rekey(paths: &Paths, out: &Out, password_stdin: bool) -> Outcome {
|
|
|
593
651
|
} else {
|
|
594
652
|
ask_password(tr("ai-vault · upgrade key parameters", "ai-vault · 升级密钥参数"), tr("master password", "主密码"))?
|
|
595
653
|
};
|
|
596
|
-
let (
|
|
654
|
+
let (payload, _old_key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
597
655
|
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
598
656
|
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
599
657
|
})?;
|
|
600
658
|
let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| Fault::Error("vault salt is corrupt".into()))?;
|
|
601
659
|
let kdf = Kdf::default();
|
|
602
660
|
let new_key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
|
|
603
|
-
let sealed = crypto::seal(&salt, kdf, &new_key, &items)?;
|
|
661
|
+
let sealed = crypto::seal(&salt, kdf, &new_key, &payload.items, &payload.config)?;
|
|
604
662
|
{
|
|
605
663
|
let _guard = StoreLock::acquire(paths)?;
|
|
606
664
|
let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
|
|
@@ -609,7 +667,7 @@ fn rekey(paths: &Paths, out: &Out, password_stdin: bool) -> Outcome {
|
|
|
609
667
|
// Other live sessions hold the old key; they cannot open the new file and
|
|
610
668
|
// will be told to unlock again. The machine session is simply re-minted.
|
|
611
669
|
let _ = session::delete_auto(paths);
|
|
612
|
-
if config
|
|
670
|
+
if payload.config.unlock.mode == UnlockMode::Never {
|
|
613
671
|
let auto = Session::new("rekey", 0, None, &sealed, &new_key);
|
|
614
672
|
session::save_auto(paths, &auto)?;
|
|
615
673
|
}
|
|
@@ -630,7 +688,6 @@ fn doctor(paths: &Paths, out: &Out) -> Outcome {
|
|
|
630
688
|
"audit": paths.audit(),
|
|
631
689
|
"display": dialog::has_display(),
|
|
632
690
|
"zenity": which("zenity"),
|
|
633
|
-
"mode": config::load(paths).unlock.mode.as_str(),
|
|
634
691
|
"auto": paths.auto_session().exists(),
|
|
635
692
|
"kdf": crypto::read_store(&paths.store()).ok().flatten().map(|s| s.kdf().n),
|
|
636
693
|
});
|
|
@@ -677,7 +734,11 @@ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_mi
|
|
|
677
734
|
let salt = crypto::random_bytes::<16>();
|
|
678
735
|
let kdf = Kdf::default();
|
|
679
736
|
let key = crypto::derive_key(&password, &salt, kdf).map_err(|e| Fault::Error(e.to_string()))?;
|
|
680
|
-
let
|
|
737
|
+
let mut config = config::Config::default();
|
|
738
|
+
if let Some(legacy) = config::take_legacy(paths) {
|
|
739
|
+
config = legacy;
|
|
740
|
+
}
|
|
741
|
+
let sealed = crypto::seal(&salt, kdf, &key, &[], &config)?;
|
|
681
742
|
{
|
|
682
743
|
let _guard = StoreLock::acquire(paths)?;
|
|
683
744
|
if paths.store().exists() {
|
|
@@ -687,13 +748,13 @@ fn init(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_mi
|
|
|
687
748
|
crypto::write_atomic(&paths.store(), &bytes)?;
|
|
688
749
|
}
|
|
689
750
|
session::ensure_session_dir(paths)?;
|
|
690
|
-
let (idle, deadline, policy) = policy(
|
|
691
|
-
let secret = signing_key(paths)?;
|
|
751
|
+
let (idle, deadline, policy) = policy(idle_min, &config);
|
|
692
752
|
let session = Session::new(requester, idle, deadline, &sealed, &key);
|
|
693
753
|
if policy.mode == UnlockMode::Never {
|
|
694
754
|
session::save_auto(paths, &session)?;
|
|
695
755
|
} else {
|
|
696
|
-
|
|
756
|
+
let signer = signer(paths)?;
|
|
757
|
+
session.save(paths, &signer)?;
|
|
697
758
|
}
|
|
698
759
|
audit::append(&paths.audit(), requester, "init", None, None);
|
|
699
760
|
let value = json!({
|
|
@@ -717,26 +778,38 @@ fn unlock(paths: &Paths, out: &Out, password_stdin: bool, requester: &str, idle_
|
|
|
717
778
|
} else {
|
|
718
779
|
ask_password(tr("ai-vault · unlock", "ai-vault · 解锁"), tr("local store master password", "本地库主密码"))?
|
|
719
780
|
};
|
|
720
|
-
let (
|
|
781
|
+
let (mut payload, key) = crypto::open_with_passphrase(&store, &password).map_err(|e| match e {
|
|
721
782
|
crypto::OpenError::WrongPassword => {
|
|
722
783
|
audit::append(&paths.audit(), requester, "unlock_failed", None, Some("bad-password"));
|
|
723
784
|
Fault::Auth("wrong master password".into())
|
|
724
785
|
}
|
|
725
786
|
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
726
787
|
})?;
|
|
788
|
+
let items = payload.items;
|
|
789
|
+
// A plaintext config.json from an older version is brought inside the
|
|
790
|
+
// store now that the password has been verified — minus anything that
|
|
791
|
+
// lowers protection, which a file edit must never grant.
|
|
792
|
+
let migrated = config::take_legacy(paths).map(|legacy| {
|
|
793
|
+
payload.config = legacy;
|
|
794
|
+
true
|
|
795
|
+
});
|
|
796
|
+
if migrated == Some(true) {
|
|
797
|
+
let salt = crypto::hex_to_bytes(&store.salt).ok_or_else(|| Fault::Error("vault salt is corrupt".into()))?;
|
|
798
|
+
let sealed = crypto::seal(&salt, store.kdf(), &key, &items, &payload.config)?;
|
|
799
|
+
let bytes = serde_json::to_vec(&sealed).map_err(|e| Fault::Error(format!("cannot serialize store: {e}")))?;
|
|
800
|
+
crypto::write_atomic(&paths.store(), &bytes)?;
|
|
801
|
+
}
|
|
727
802
|
session::ensure_session_dir(paths)?;
|
|
728
803
|
session::sweep(paths);
|
|
729
|
-
let (idle, deadline, policy) = policy(
|
|
730
|
-
// A host that did not pass a secret gets a fresh one to keep for this
|
|
731
|
-
// session: it is the only thing that can sign later edits to the file.
|
|
804
|
+
let (idle, deadline, policy) = policy(idle_min, &payload.config);
|
|
732
805
|
// The host brings its own secret (so the same process can sign later
|
|
733
806
|
// calls); everyone else is signed with the wrap key.
|
|
734
|
-
let secret = signing_key(paths)?;
|
|
735
807
|
let session = Session::new(requester, idle, deadline, &store, &key);
|
|
736
808
|
if policy.mode == UnlockMode::Never {
|
|
737
809
|
session::save_auto(paths, &session)?;
|
|
738
810
|
} else {
|
|
739
|
-
|
|
811
|
+
let signer = signer(paths)?;
|
|
812
|
+
session.save(paths, &signer)?;
|
|
740
813
|
}
|
|
741
814
|
audit::append(&paths.audit(), requester, "unlock", None, Some(policy.mode.as_str()));
|
|
742
815
|
let value = json!({
|
|
@@ -759,6 +832,7 @@ fn setting_key(raw: &str) -> Option<&'static str> {
|
|
|
759
832
|
match raw.trim().to_lowercase().as_str() {
|
|
760
833
|
"vault.unlock" | "vault.mode" | "unlock" | "mode" => Some("vault.unlock"),
|
|
761
834
|
"vault.hours" | "hours" => Some("vault.hours"),
|
|
835
|
+
"vault.confirm" | "confirm" => Some("vault.confirm"),
|
|
762
836
|
"bitwarden.unlock" | "bitwarden.mode" | "bw.unlock" | "bw.mode" => Some("bitwarden.unlock"),
|
|
763
837
|
"bitwarden.hours" | "bw.hours" => Some("bitwarden.hours"),
|
|
764
838
|
"bitwarden.import" | "bw.import" | "import" => Some("bitwarden.import"),
|
|
@@ -776,6 +850,7 @@ fn settings_value(config: &config::Config, paths: &Paths) -> serde_json::Value {
|
|
|
776
850
|
"vault": {
|
|
777
851
|
"unlock": config.unlock.mode.as_str(),
|
|
778
852
|
"hours": config.unlock.hours,
|
|
853
|
+
"confirm": config.unlock.confirm,
|
|
779
854
|
"auto": paths.auto_session().exists(),
|
|
780
855
|
},
|
|
781
856
|
"bitwarden": {
|
|
@@ -799,6 +874,11 @@ fn settings_human(config: &config::Config, paths: &Paths) -> String {
|
|
|
799
874
|
[
|
|
800
875
|
format!("vault.unlock: {} (never | time | session)", config.unlock.mode.as_str()),
|
|
801
876
|
format!("vault.hours: {}{}", config.unlock.hours, tr(" (time mode)", " (time 模式)")),
|
|
877
|
+
format!(
|
|
878
|
+
"vault.confirm: {}{}",
|
|
879
|
+
config.unlock.confirm,
|
|
880
|
+
tr(" (a window per read while unlocked)", " (解锁后每次读取弹确认窗)")
|
|
881
|
+
),
|
|
802
882
|
format!("{} {}", tr("vault machine-wide session:", "vault 机器级会话:"), if paths.auto_session().exists() { tr("yes (no password)", "有(免密)") } else { tr("no", "无") }),
|
|
803
883
|
format!("bitwarden.unlock: {} (never | time | session)", config.bitwarden.store.unlock.as_str()),
|
|
804
884
|
format!("bitwarden.hours: {}", config.bitwarden.store.hours),
|
|
@@ -826,12 +906,18 @@ fn settings_human(config: &config::Config, paths: &Paths) -> String {
|
|
|
826
906
|
fn settings(
|
|
827
907
|
paths: &Paths,
|
|
828
908
|
out: &Out,
|
|
909
|
+
token: Option<&str>,
|
|
829
910
|
key: Option<&str>,
|
|
830
911
|
value: Option<&str>,
|
|
831
912
|
hours: Option<i64>,
|
|
832
913
|
password_stdin: bool,
|
|
833
914
|
) -> Outcome {
|
|
834
|
-
|
|
915
|
+
// The settings live inside the store's ciphertext: reading them needs the
|
|
916
|
+
// store's key, i.e. an unlocked session. That is the whole point — there
|
|
917
|
+
// is no file an agent could edit.
|
|
918
|
+
let session = load_session(paths, token)?;
|
|
919
|
+
let store = open_store(paths)?;
|
|
920
|
+
let mut config = payload_with(&session, &store)?.config;
|
|
835
921
|
|
|
836
922
|
let Some(raw_key) = key.filter(|k| !k.trim().is_empty()) else {
|
|
837
923
|
let value = settings_value(&config, paths);
|
|
@@ -848,6 +934,7 @@ fn settings(
|
|
|
848
934
|
let shown = match key {
|
|
849
935
|
"vault.unlock" => config.unlock.mode.as_str().to_string(),
|
|
850
936
|
"vault.hours" => config.unlock.hours.to_string(),
|
|
937
|
+
"vault.confirm" => config.unlock.confirm.to_string(),
|
|
851
938
|
"bitwarden.unlock" => config.bitwarden.store.unlock.as_str().to_string(),
|
|
852
939
|
"bitwarden.hours" => config.bitwarden.store.hours.to_string(),
|
|
853
940
|
"ente.unlock" => config.ente.unlock.as_str().to_string(),
|
|
@@ -862,19 +949,13 @@ fn settings(
|
|
|
862
949
|
"vault.unlock" => {
|
|
863
950
|
let mode = UnlockMode::parse(raw_value)
|
|
864
951
|
.ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
|
|
865
|
-
let store = open_store(paths)?;
|
|
866
952
|
// Changing when the vault opens is a security decision: always verify.
|
|
867
|
-
let
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
crypto::OpenError::WrongPassword => Fault::Auth("wrong master password".into()),
|
|
874
|
-
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
875
|
-
})?;
|
|
876
|
-
config.unlock = UnlockPolicy { mode, hours: hours.unwrap_or(config.unlock.hours).clamp(1, 24 * 90) };
|
|
877
|
-
config::save(paths, &config)?;
|
|
953
|
+
let (payload, vault_key) = verify_master(paths, &store, password_stdin, tr("switching the unlock policy", "切换解锁模式"))?;
|
|
954
|
+
config.unlock.mode = mode;
|
|
955
|
+
if let Some(hours) = hours {
|
|
956
|
+
config.unlock.hours = hours.clamp(1, 24 * 90);
|
|
957
|
+
}
|
|
958
|
+
config_write(paths, &session, &config)?;
|
|
878
959
|
session::ensure_session_dir(paths)?;
|
|
879
960
|
if mode == UnlockMode::Never {
|
|
880
961
|
let auto = Session::new("mode", 0, None, &store, &vault_key);
|
|
@@ -882,6 +963,7 @@ fn settings(
|
|
|
882
963
|
} else {
|
|
883
964
|
session::delete_auto(paths);
|
|
884
965
|
}
|
|
966
|
+
let _ = payload;
|
|
885
967
|
audit::append(&paths.audit(), "cli", "mode", None, Some(mode.as_str()));
|
|
886
968
|
}
|
|
887
969
|
"vault.hours" => {
|
|
@@ -889,16 +971,36 @@ fn settings(
|
|
|
889
971
|
.parse()
|
|
890
972
|
.map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
|
|
891
973
|
config.unlock.hours = hours.clamp(1, 24 * 90);
|
|
892
|
-
|
|
974
|
+
config_write(paths, &session, &config)?;
|
|
975
|
+
}
|
|
976
|
+
"vault.confirm" => {
|
|
977
|
+
// Turning the per-read window off is a security decision, priced
|
|
978
|
+
// like the unlock policy: the master password.
|
|
979
|
+
let on = matches!(raw_value, "true" | "1" | "yes" | "on" | "ask")
|
|
980
|
+
|| if matches!(raw_value, "false" | "0" | "no" | "off") {
|
|
981
|
+
false
|
|
982
|
+
} else {
|
|
983
|
+
return Err(Fault::Usage(format!("\"{raw_value}\" is not true or false")));
|
|
984
|
+
};
|
|
985
|
+
if !on {
|
|
986
|
+
verify_master(paths, &store, password_stdin, tr("turn off the per-read confirmation", "关闭每次读取的确认窗"))?;
|
|
987
|
+
}
|
|
988
|
+
config.unlock.confirm = on;
|
|
989
|
+
config_write(paths, &session, &config)?;
|
|
990
|
+
audit::append(&paths.audit(), "cli", "settings", None, Some(if on { "confirm=on" } else { "confirm=off" }));
|
|
893
991
|
}
|
|
894
992
|
"bitwarden.unlock" => {
|
|
895
993
|
let mode = UnlockMode::parse(raw_value)
|
|
896
994
|
.ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
|
|
995
|
+
// Keeping the bw session key on disk is a downgrade of its own.
|
|
996
|
+
if mode != UnlockMode::Session {
|
|
997
|
+
verify_master(paths, &store, password_stdin, tr("keeping the Bitwarden session on disk", "把 Bitwarden 会话落盘"))?;
|
|
998
|
+
}
|
|
897
999
|
config.bitwarden.store.unlock = mode;
|
|
898
1000
|
if let Some(hours) = hours {
|
|
899
1001
|
config.bitwarden.store.hours = hours.clamp(1, 24 * 90);
|
|
900
1002
|
}
|
|
901
|
-
|
|
1003
|
+
config_write(paths, &session, &config)?;
|
|
902
1004
|
// Going back to per-session must not leave a key on disk.
|
|
903
1005
|
if mode == UnlockMode::Session {
|
|
904
1006
|
sealed::clear(paths, Kind::Bitwarden);
|
|
@@ -909,16 +1011,19 @@ fn settings(
|
|
|
909
1011
|
.parse()
|
|
910
1012
|
.map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
|
|
911
1013
|
config.bitwarden.store.hours = hours.clamp(1, 24 * 90);
|
|
912
|
-
|
|
1014
|
+
config_write(paths, &session, &config)?;
|
|
913
1015
|
}
|
|
914
1016
|
"ente.unlock" => {
|
|
915
1017
|
let mode = UnlockMode::parse(raw_value)
|
|
916
1018
|
.ok_or_else(|| Fault::Usage(format!("unknown mode \"{raw_value}\" — never, time or session")))?;
|
|
1019
|
+
if mode != UnlockMode::Session {
|
|
1020
|
+
verify_master(paths, &store, password_stdin, tr("keeping the Ente key on disk", "把 Ente 密钥落盘"))?;
|
|
1021
|
+
}
|
|
917
1022
|
config.ente.unlock = mode;
|
|
918
1023
|
if let Some(hours) = hours {
|
|
919
1024
|
config.ente.hours = hours.clamp(1, 24 * 90);
|
|
920
1025
|
}
|
|
921
|
-
|
|
1026
|
+
config_write(paths, &session, &config)?;
|
|
922
1027
|
if mode == UnlockMode::Session {
|
|
923
1028
|
sealed::clear(paths, Kind::Ente);
|
|
924
1029
|
}
|
|
@@ -928,14 +1033,18 @@ fn settings(
|
|
|
928
1033
|
.parse()
|
|
929
1034
|
.map_err(|_| Fault::Usage(format!("\"{raw_value}\" is not a number of hours")))?;
|
|
930
1035
|
config.ente.hours = hours.clamp(1, 24 * 90);
|
|
931
|
-
|
|
1036
|
+
config_write(paths, &session, &config)?;
|
|
932
1037
|
}
|
|
933
1038
|
_ => {
|
|
934
1039
|
let import = ImportPolicy::parse(raw_value).ok_or_else(|| {
|
|
935
1040
|
Fault::Usage(format!("unknown import policy \"{raw_value}\" — ask, always or never"))
|
|
936
1041
|
})?;
|
|
1042
|
+
// "always" imports a Bitwarden hit with no window: a downgrade.
|
|
1043
|
+
if import == ImportPolicy::Always {
|
|
1044
|
+
verify_master(paths, &store, password_stdin, tr("importing Bitwarden hits without asking", "不询问就导入 Bitwarden 条目"))?;
|
|
1045
|
+
}
|
|
937
1046
|
config.bitwarden.import = import;
|
|
938
|
-
|
|
1047
|
+
config_write(paths, &session, &config)?;
|
|
939
1048
|
}
|
|
940
1049
|
}
|
|
941
1050
|
|
|
@@ -944,29 +1053,53 @@ fn settings(
|
|
|
944
1053
|
Ok(())
|
|
945
1054
|
}
|
|
946
1055
|
|
|
1056
|
+
/// Ask for the master password and prove it against the store. Used for
|
|
1057
|
+
/// every change that lowers protection. Returns the opened payload and the
|
|
1058
|
+
/// key, for the one caller that mints the machine-wide session.
|
|
1059
|
+
fn verify_master(
|
|
1060
|
+
paths: &Paths,
|
|
1061
|
+
store: &crypto::StoreFile,
|
|
1062
|
+
password_stdin: bool,
|
|
1063
|
+
why: &str,
|
|
1064
|
+
) -> Result<(crypto::Payload, crypto::Key), Fault> {
|
|
1065
|
+
let password = if password_stdin {
|
|
1066
|
+
read_password()?
|
|
1067
|
+
} else {
|
|
1068
|
+
ask_password(tr("ai-vault · master password", "ai-vault · 主密码"), why)?
|
|
1069
|
+
};
|
|
1070
|
+
crypto::open_with_passphrase(store, &password).map_err(|e| match e {
|
|
1071
|
+
crypto::OpenError::WrongPassword => {
|
|
1072
|
+
audit::append(&paths.audit(), "cli", "settings", None, Some("denied=bad-password"));
|
|
1073
|
+
Fault::Auth("wrong master password".into())
|
|
1074
|
+
}
|
|
1075
|
+
crypto::OpenError::Broken(message) => Fault::Error(message),
|
|
1076
|
+
})
|
|
1077
|
+
}
|
|
1078
|
+
|
|
947
1079
|
/// `/vault mode` is a shortcut for the `vault.unlock` setting.
|
|
948
1080
|
fn mode(
|
|
949
1081
|
paths: &Paths,
|
|
950
1082
|
out: &Out,
|
|
1083
|
+
token: Option<&str>,
|
|
951
1084
|
action: &str,
|
|
952
1085
|
value: Option<&str>,
|
|
953
1086
|
hours: Option<i64>,
|
|
954
1087
|
password_stdin: bool,
|
|
955
1088
|
) -> Outcome {
|
|
956
1089
|
match action.trim() {
|
|
957
|
-
"" | "get" | "status" => settings(paths, out, Some("vault.unlock"), None, None, password_stdin),
|
|
958
|
-
"set" => settings(paths, out, Some("vault.unlock"), value, hours, password_stdin),
|
|
1090
|
+
"" | "get" | "status" => settings(paths, out, token, Some("vault.unlock"), None, None, password_stdin),
|
|
1091
|
+
"set" => settings(paths, out, token, Some("vault.unlock"), value, hours, password_stdin),
|
|
959
1092
|
other => Err(Fault::Usage(format!("unknown mode action \"{other}\""))),
|
|
960
1093
|
}
|
|
961
1094
|
}
|
|
962
1095
|
|
|
963
|
-
fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome {
|
|
1096
|
+
fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str, token: Option<&str>) -> Outcome {
|
|
964
1097
|
match action.trim() {
|
|
965
1098
|
"" | "get" => {
|
|
966
1099
|
let stored = sealed::load(paths, kind)?
|
|
967
|
-
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret — save one first",
|
|
1100
|
+
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret — save one first", secret_kind_label(kind))))?;
|
|
968
1101
|
let key = sealed::key(paths, kind)?
|
|
969
|
-
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret",
|
|
1102
|
+
.ok_or_else(|| Fault::Auth(format!("no persisted {} secret", secret_kind_label(kind))))?;
|
|
970
1103
|
out.value(
|
|
971
1104
|
json!({ "ok": true, "key": key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
|
|
972
1105
|
|| key,
|
|
@@ -978,8 +1111,15 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
|
|
|
978
1111
|
if key.is_empty() {
|
|
979
1112
|
return Err(Fault::Usage("bw-session put expects the session key on stdin".into()));
|
|
980
1113
|
}
|
|
981
|
-
let
|
|
982
|
-
|
|
1114
|
+
let session = load_session(paths, token)?;
|
|
1115
|
+
let store = open_store(paths)?;
|
|
1116
|
+
let payload = payload_with(&session, &store)?;
|
|
1117
|
+
let policy = match kind {
|
|
1118
|
+
Kind::Bitwarden => payload.config.bitwarden.store,
|
|
1119
|
+
Kind::Ente => payload.config.ente,
|
|
1120
|
+
};
|
|
1121
|
+
let expires_at = sealed::save(paths, kind, &key, policy)?;
|
|
1122
|
+
audit::append(&paths.audit(), "cli", "sealed", None, Some(secret_kind_label(kind)));
|
|
983
1123
|
out.value(json!({ "ok": true, "expiresAt": expires_at }), || {
|
|
984
1124
|
match expires_at {
|
|
985
1125
|
Some(at) => format!("saved (expires in {} min)", ((at - session::now_ms()) / 60_000).max(0)),
|
|
@@ -990,7 +1130,7 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
|
|
|
990
1130
|
}
|
|
991
1131
|
"clear" | "delete" => {
|
|
992
1132
|
let removed = sealed::clear(paths, kind);
|
|
993
|
-
audit::append(&paths.audit(), "cli", "sealed", None, Some(
|
|
1133
|
+
audit::append(&paths.audit(), "cli", "sealed", None, Some(secret_kind_label(kind)));
|
|
994
1134
|
out.value(json!({ "ok": true, "removed": removed }), || {
|
|
995
1135
|
if removed { "cleared".to_string() } else { "nothing stored".to_string() }
|
|
996
1136
|
});
|
|
@@ -1013,7 +1153,7 @@ fn status(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
|
|
|
1013
1153
|
.iter()
|
|
1014
1154
|
.map(|(name, until)| (name.clone(), json!({ "expiresAt": until, "leftMs": until - now })))
|
|
1015
1155
|
.collect();
|
|
1016
|
-
let policy =
|
|
1156
|
+
let policy = payload_with(&session, &store)?.config.unlock;
|
|
1017
1157
|
let auto = session::load_auto(paths)
|
|
1018
1158
|
.ok()
|
|
1019
1159
|
.flatten()
|
|
@@ -1027,6 +1167,7 @@ fn status(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
|
|
|
1027
1167
|
"expiresAt": session.expiry(),
|
|
1028
1168
|
"mode": policy.mode.as_str(),
|
|
1029
1169
|
"hours": policy.hours,
|
|
1170
|
+
"confirm": policy.confirm,
|
|
1030
1171
|
"auto": auto,
|
|
1031
1172
|
"store": paths.store(),
|
|
1032
1173
|
"grants": grants,
|
|
@@ -1090,7 +1231,15 @@ fn list(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
|
|
|
1090
1231
|
}
|
|
1091
1232
|
items
|
|
1092
1233
|
.iter()
|
|
1093
|
-
.map(|i|
|
|
1234
|
+
.map(|i| {
|
|
1235
|
+
format!(
|
|
1236
|
+
"{}\t{}\t{}\t{}",
|
|
1237
|
+
i.name,
|
|
1238
|
+
kind_label(i.r#type),
|
|
1239
|
+
i.username.clone().unwrap_or_default(),
|
|
1240
|
+
i.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default()
|
|
1241
|
+
)
|
|
1242
|
+
})
|
|
1094
1243
|
.collect::<Vec<_>>()
|
|
1095
1244
|
.join("\n")
|
|
1096
1245
|
});
|
|
@@ -1108,7 +1257,8 @@ fn get(
|
|
|
1108
1257
|
) -> Outcome {
|
|
1109
1258
|
let mut session = load_session(paths, token.as_deref())?;
|
|
1110
1259
|
let store = open_store(paths)?;
|
|
1111
|
-
let
|
|
1260
|
+
let payload = payload_with(&session, &store)?;
|
|
1261
|
+
let items = payload.items;
|
|
1112
1262
|
let item = store::find(&items, name).cloned().ok_or_else(|| {
|
|
1113
1263
|
let names = items.iter().map(|i| i.name.clone()).collect::<Vec<_>>().join(", ");
|
|
1114
1264
|
Fault::Error(format!("no such entry: \"{name}\". available: {}", if names.is_empty() { "(empty)" } else { &names }))
|
|
@@ -1118,8 +1268,17 @@ fn get(
|
|
|
1118
1268
|
// `never` mode is the "the agent may use these freely" mode: the machine-wide
|
|
1119
1269
|
// session is the authorization, so no window opens on each read.
|
|
1120
1270
|
let auto = token.as_deref().map_or(true, |t| t.trim().is_empty());
|
|
1271
|
+
// `vault.confirm = false`: the master password that opened this session is
|
|
1272
|
+
// the approval. Safe for exactly that reason — a session the extension
|
|
1273
|
+
// opened can only exist because the user typed the password (a token the
|
|
1274
|
+
// model finds on disk is useless without the host secret). Every read is
|
|
1275
|
+
// still written to the audit log, entry by entry.
|
|
1276
|
+
let no_confirm = payload.config.unlock.confirm == false;
|
|
1121
1277
|
let via = if auto {
|
|
1122
1278
|
"no-password"
|
|
1279
|
+
} else if no_confirm {
|
|
1280
|
+
audit::append(&paths.audit(), &session.requester, "read_allow", Some(&item.name), Some("confirm-off"));
|
|
1281
|
+
"unlocked-no-confirm"
|
|
1123
1282
|
} else if session.grant(&item.name, now).is_some() {
|
|
1124
1283
|
"existing-grant"
|
|
1125
1284
|
} else {
|
|
@@ -1128,7 +1287,7 @@ fn get(
|
|
|
1128
1287
|
let message = format!(
|
|
1129
1288
|
"{} {}\n{} {}\n{} {}\n\n{}",
|
|
1130
1289
|
tr("Entry:", "条目:"),
|
|
1131
|
-
dialog::for_dialog(&item.name, 80),
|
|
1290
|
+
format!("{} ({})", dialog::for_dialog(&item.name, 80), kind_label(item.r#type)),
|
|
1132
1291
|
tr("Requester:", "请求方:"),
|
|
1133
1292
|
dialog::for_dialog(&session.requester, 40),
|
|
1134
1293
|
tr("Reason:", "原因:"),
|
|
@@ -1196,46 +1355,127 @@ fn get(
|
|
|
1196
1355
|
|
|
1197
1356
|
struct AddRequest {
|
|
1198
1357
|
name: String,
|
|
1358
|
+
r#type: Option<String>,
|
|
1199
1359
|
username: Option<String>,
|
|
1200
1360
|
uri: Option<String>,
|
|
1201
1361
|
notes: Option<String>,
|
|
1362
|
+
fields: Vec<String>,
|
|
1363
|
+
secrets: Vec<String>,
|
|
1202
1364
|
password_stdin: bool,
|
|
1203
1365
|
yes: bool,
|
|
1204
1366
|
}
|
|
1205
1367
|
|
|
1368
|
+
/// Parse a type name the way a human writes it: login, note, secure-note,
|
|
1369
|
+
/// ssh key, "SSH key", drivers licence …
|
|
1370
|
+
fn parse_item_type(raw: &str) -> Option<ItemType> {
|
|
1371
|
+
let key: String = raw.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase();
|
|
1372
|
+
Some(match key.as_str() {
|
|
1373
|
+
"login" | "password" | "" => ItemType::Login,
|
|
1374
|
+
"note" | "securenote" => ItemType::SecureNote,
|
|
1375
|
+
"card" | "creditcard" => ItemType::Card,
|
|
1376
|
+
"identity" | "person" => ItemType::Identity,
|
|
1377
|
+
"sshkey" | "ssh" | "key" => ItemType::SshKey,
|
|
1378
|
+
"bankaccount" | "bank" => ItemType::BankAccount,
|
|
1379
|
+
"driverslicense" | "driverlicense" | "license" | "drivinglicence" => ItemType::DriversLicense,
|
|
1380
|
+
"passport" => ItemType::Passport,
|
|
1381
|
+
_ => return None,
|
|
1382
|
+
})
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1206
1385
|
fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outcome {
|
|
1207
1386
|
let mut session = load_session(paths, token.as_deref())?;
|
|
1208
1387
|
let name = req.name.trim().to_string();
|
|
1209
1388
|
if name.is_empty() {
|
|
1210
1389
|
return Err(Fault::Usage("an entry needs a name".into()));
|
|
1211
1390
|
}
|
|
1391
|
+
let kind = match req.r#type.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
|
|
1392
|
+
None => ItemType::Login,
|
|
1393
|
+
Some(raw) => parse_item_type(raw).ok_or_else(|| {
|
|
1394
|
+
Fault::Usage(format!(
|
|
1395
|
+
"unknown type \"{raw}\" — login, note, card, identity, sshkey, bankaccount, driverslicense, passport"
|
|
1396
|
+
))
|
|
1397
|
+
})?,
|
|
1398
|
+
};
|
|
1212
1399
|
let store = open_store(paths)?;
|
|
1213
1400
|
let items = items_with(&session, &store)?;
|
|
1214
1401
|
let existing = store::find(&items, &name).cloned();
|
|
1402
|
+
// Updating an entry of another type replaces its data block: say so in the window.
|
|
1403
|
+
let type_changes = existing.as_ref().is_some_and(|item| item.r#type != kind);
|
|
1404
|
+
|
|
1405
|
+
// --field NAME=VALUE pairs, by the type's own field names.
|
|
1406
|
+
let mut data: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
|
|
1407
|
+
let mut to_type: Vec<String> = Vec::new();
|
|
1408
|
+
for raw in &req.fields {
|
|
1409
|
+
let (field, value) = match raw.split_once('=') {
|
|
1410
|
+
Some((f, v)) => (f.trim().to_string(), Some(v.to_string())),
|
|
1411
|
+
None => (raw.trim().to_string(), None),
|
|
1412
|
+
};
|
|
1413
|
+
let field = resolve_field_name(kind, &field)
|
|
1414
|
+
.ok_or_else(|| Fault::Usage(format!("\"{field}\" is not a field of a {}", kind_label(kind))))?;
|
|
1415
|
+
match value {
|
|
1416
|
+
Some(v) => {
|
|
1417
|
+
data.insert(field, serde_json::Value::String(v));
|
|
1418
|
+
}
|
|
1419
|
+
None => to_type.push(field),
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
// Host-supplied hidden fields (the host asked the user in its own UI).
|
|
1423
|
+
for raw in &req.secrets {
|
|
1424
|
+
let (field, value) = raw.split_once('=').ok_or_else(|| Fault::Usage("--secret expects NAME=VALUE".into()))?;
|
|
1425
|
+
let field = resolve_field_name(kind, field.trim())
|
|
1426
|
+
.ok_or_else(|| Fault::Usage(format!("\"{}\" is not a field of a {}", field.trim(), kind_label(kind))))?;
|
|
1427
|
+
if !is_secret_field(kind, &field) {
|
|
1428
|
+
return Err(Fault::Usage(format!("--secret is for hidden fields; \"{field}\" can go in --field")));
|
|
1429
|
+
}
|
|
1430
|
+
data.insert(field, serde_json::Value::String(value.to_string()));
|
|
1431
|
+
}
|
|
1432
|
+
// The conventional flags feed the login fields and the shared notes.
|
|
1433
|
+
if kind == ItemType::Login {
|
|
1434
|
+
if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
1435
|
+
data.insert("username".into(), serde_json::Value::String(user.to_string()));
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
let notes = req.notes.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
|
|
1215
1439
|
|
|
1216
1440
|
if !req.yes {
|
|
1217
1441
|
let mut meta = Vec::new();
|
|
1442
|
+
let shown = dialog::for_dialog(&name, 80);
|
|
1443
|
+
let action = match &existing {
|
|
1444
|
+
Some(_) if type_changes => tr_owned(
|
|
1445
|
+
format!("Replace \"{shown}\" with a {} entry.", kind_label(kind)),
|
|
1446
|
+
format!("把「{shown}」改成{}条目。", kind_label(kind)),
|
|
1447
|
+
),
|
|
1448
|
+
Some(_) => tr_owned(format!("Update the existing entry \"{shown}\"."), format!("更新已有条目「{shown}」。")),
|
|
1449
|
+
None => tr_owned(format!("Create a {} entry \"{shown}\".", kind_label(kind)), format!("新建{}条目「{shown}」。", kind_label(kind))),
|
|
1450
|
+
};
|
|
1451
|
+
for (field, value) in &data {
|
|
1452
|
+
let secret = is_secret_field(kind, field);
|
|
1453
|
+
meta.push(format!(
|
|
1454
|
+
"{} {}",
|
|
1455
|
+
field,
|
|
1456
|
+
if secret { "••••".to_string() } else { dialog::for_dialog(value.as_str().unwrap_or(""), 120) }
|
|
1457
|
+
));
|
|
1458
|
+
}
|
|
1459
|
+
for field in &to_type {
|
|
1460
|
+
meta.push(format!("{field} ••••"));
|
|
1461
|
+
}
|
|
1218
1462
|
if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
1219
|
-
|
|
1463
|
+
if kind != ItemType::Login {
|
|
1464
|
+
meta.push(format!("{} {}", tr("Username:", "用户名:"), dialog::for_dialog(user, 60)));
|
|
1465
|
+
}
|
|
1220
1466
|
}
|
|
1221
1467
|
if let Some(uri) = req.uri.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
|
|
1222
1468
|
meta.push(format!("URI: {}", dialog::for_dialog(uri, 120)));
|
|
1223
1469
|
}
|
|
1224
|
-
if let Some(notes) =
|
|
1470
|
+
if let Some(notes) = notes.as_deref() {
|
|
1225
1471
|
meta.push(format!("{} {}", tr("Notes:", "备注:"), dialog::for_dialog(notes, 120)));
|
|
1226
1472
|
}
|
|
1227
|
-
let shown = dialog::for_dialog(&name, 80);
|
|
1228
|
-
let action = if existing.is_some() {
|
|
1229
|
-
tr_owned(format!("Update the existing entry \"{shown}\"."), format!("更新已有条目「{shown}」。"))
|
|
1230
|
-
} else {
|
|
1231
|
-
tr_owned(format!("Create the entry \"{shown}\"."), format!("新建条目「{shown}」。"))
|
|
1232
|
-
};
|
|
1233
1473
|
let message = format!(
|
|
1234
1474
|
"{action}{}\n{}",
|
|
1235
1475
|
if meta.is_empty() { String::new() } else { format!("\n{}", meta.join("\n")) },
|
|
1236
1476
|
tr(
|
|
1237
|
-
"A window opens next for
|
|
1238
|
-
"
|
|
1477
|
+
"A window opens next for each hidden field. Nothing enters the conversation.",
|
|
1478
|
+
"接下来每个隐藏字段弹一个窗口。密码不会进入对话。"
|
|
1239
1479
|
)
|
|
1240
1480
|
);
|
|
1241
1481
|
match dialog::confirm(tr("ai-vault · save to local store", "ai-vault · 保存到本地库"), &message) {
|
|
@@ -1245,52 +1485,134 @@ fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outc
|
|
|
1245
1485
|
}
|
|
1246
1486
|
}
|
|
1247
1487
|
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1488
|
+
// Hidden fields: typed in a dialog (or read from stdin for the primary one).
|
|
1489
|
+
// On an update, a secret the caller did not mention is left as stored; only
|
|
1490
|
+
// a new entry (or a type change) needs every secret typed.
|
|
1491
|
+
let primary = kind.primary_field();
|
|
1492
|
+
let fresh = existing.as_ref().map_or(true, |item| item.r#type != kind);
|
|
1493
|
+
let mut secret_fields: Vec<String> = to_type;
|
|
1494
|
+
if fresh {
|
|
1495
|
+
if let Some(field) = primary {
|
|
1496
|
+
if !data.contains_key(field) {
|
|
1497
|
+
secret_fields.push(field.to_string());
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
} else if let Some(item) = &existing {
|
|
1501
|
+
// Carry over the stored data block so `apply` does not read the absent
|
|
1502
|
+
// fields as "clear"; the draft's own values still win.
|
|
1503
|
+
for (field, value) in item.data.clone().unwrap_or_default() {
|
|
1504
|
+
data.entry(field).or_insert(value);
|
|
1257
1505
|
}
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1506
|
+
}
|
|
1507
|
+
for field in secret_fields {
|
|
1508
|
+
let password = if req.password_stdin && Some(field.as_str()) == primary {
|
|
1509
|
+
read_password()?
|
|
1510
|
+
} else {
|
|
1511
|
+
ask_field_password(&field, tr("ai-vault · password", "ai-vault · 密码"), &format!("{name} · {field}"))?
|
|
1512
|
+
};
|
|
1513
|
+
if password.is_empty() {
|
|
1514
|
+
return Err(Fault::Denied("cancelled: no password entered".into()));
|
|
1515
|
+
}
|
|
1516
|
+
data.insert(field, serde_json::Value::String(password));
|
|
1517
|
+
}
|
|
1518
|
+
if kind == ItemType::SecureNote && notes.is_none() && data.is_empty() {
|
|
1519
|
+
// A secure note is its notes; a dialog for the body when none was given.
|
|
1520
|
+
let body = match dialog::prompt_text(tr("ai-vault · note", "ai-vault · 备注"), tr("the note's contents", "备注内容")) {
|
|
1521
|
+
Answer::Value(text) => text,
|
|
1522
|
+
Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
|
|
1523
|
+
Answer::NoUi => return Err(Fault::NeedsUi("text")),
|
|
1524
|
+
};
|
|
1525
|
+
if body.trim().is_empty() {
|
|
1526
|
+
return Err(Fault::Usage("a note needs contents (--notes)".into()));
|
|
1527
|
+
}
|
|
1528
|
+
let notes = Some(body);
|
|
1529
|
+
return finish_add(paths, out, &mut session, Draft {
|
|
1530
|
+
name: name.clone(),
|
|
1531
|
+
r#type: kind,
|
|
1532
|
+
notes,
|
|
1533
|
+
data: None,
|
|
1534
|
+
..Default::default()
|
|
1535
|
+
}, &name);
|
|
1266
1536
|
}
|
|
1267
1537
|
|
|
1268
|
-
let
|
|
1269
|
-
let uri = req.uri.map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
|
|
1270
|
-
let notes = req.notes.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
|
|
1538
|
+
let uris = req.uri.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()).map(|u| vec![u]);
|
|
1271
1539
|
let draft = Draft {
|
|
1272
|
-
id: None,
|
|
1273
1540
|
name: name.clone(),
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1541
|
+
r#type: kind,
|
|
1542
|
+
username: if kind == ItemType::Login { req.username.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()) } else { None },
|
|
1543
|
+
password: String::new(),
|
|
1544
|
+
uris,
|
|
1545
|
+
data: if data.is_empty() { None } else { Some(data) },
|
|
1277
1546
|
notes,
|
|
1278
|
-
|
|
1547
|
+
..Default::default()
|
|
1279
1548
|
};
|
|
1549
|
+
finish_add(paths, out, &mut session, draft, &name)
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
fn finish_add(paths: &Paths, out: &Out, session: &mut Session, draft: Draft, name: &str) -> Outcome {
|
|
1280
1553
|
let mut inserted = false;
|
|
1281
|
-
|
|
1554
|
+
let kind = draft.r#type;
|
|
1555
|
+
mutate(paths, session, |items, now| {
|
|
1282
1556
|
inserted = store::apply(items, draft, now);
|
|
1283
1557
|
Ok(())
|
|
1284
1558
|
})?;
|
|
1285
1559
|
session.last_active = session::now_ms();
|
|
1286
|
-
persist(paths,
|
|
1287
|
-
audit::append(&paths.audit(), &session.requester, "add", Some(
|
|
1288
|
-
|
|
1289
|
-
|
|
1560
|
+
persist(paths, session);
|
|
1561
|
+
audit::append(&paths.audit(), &session.requester, "add", Some(name), Some(kind_label(kind)));
|
|
1562
|
+
let mut value = json!({ "ok": true, "item": name, "type": kind_label(kind), "created": inserted });
|
|
1563
|
+
if let Some(record) = value.as_object_mut() {
|
|
1564
|
+
record.insert("fields".into(), json!(kind.fields()));
|
|
1565
|
+
}
|
|
1566
|
+
out.value(value, || {
|
|
1567
|
+
format!(
|
|
1568
|
+
"saved \"{name}\" as a {} (hidden fields typed in the dialog, not shown)",
|
|
1569
|
+
kind_label(kind)
|
|
1570
|
+
)
|
|
1290
1571
|
});
|
|
1291
1572
|
Ok(())
|
|
1292
1573
|
}
|
|
1293
1574
|
|
|
1575
|
+
/// A type's field by the name a human typed (case- and separator-insensitive).
|
|
1576
|
+
fn resolve_field_name(kind: ItemType, raw: &str) -> Option<String> {
|
|
1577
|
+
let key: String = raw.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase();
|
|
1578
|
+
kind.fields()
|
|
1579
|
+
.iter()
|
|
1580
|
+
.find(|f| f.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase() == key)
|
|
1581
|
+
.map(|f| f.to_string())
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/// Fields whose value must never be printed in a window or in `list`.
|
|
1585
|
+
pub(crate) fn is_secret_field(kind: ItemType, field: &str) -> bool {
|
|
1586
|
+
matches!(
|
|
1587
|
+
(kind, field),
|
|
1588
|
+
(_, "password")
|
|
1589
|
+
| (_, "privateKey")
|
|
1590
|
+
| (ItemType::Card, "code")
|
|
1591
|
+
| (ItemType::Card, "number")
|
|
1592
|
+
| (ItemType::BankAccount, "pin")
|
|
1593
|
+
| (ItemType::BankAccount, "accountNumber")
|
|
1594
|
+
| (ItemType::BankAccount, "routingNumber")
|
|
1595
|
+
| (_, "ssn")
|
|
1596
|
+
| (_, "licenseNumber")
|
|
1597
|
+
| (_, "passportNumber")
|
|
1598
|
+
| (ItemType::Passport, "nationalIdentificationNumber")
|
|
1599
|
+
| (_, "totp")
|
|
1600
|
+
)
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
fn kind_label(kind: ItemType) -> &'static str {
|
|
1604
|
+
match kind {
|
|
1605
|
+
ItemType::Login => "login",
|
|
1606
|
+
ItemType::SecureNote => "note",
|
|
1607
|
+
ItemType::Card => "card",
|
|
1608
|
+
ItemType::Identity => "identity",
|
|
1609
|
+
ItemType::SshKey => "SSH key",
|
|
1610
|
+
ItemType::BankAccount => "bank account",
|
|
1611
|
+
ItemType::DriversLicense => "driver's licence",
|
|
1612
|
+
ItemType::Passport => "passport",
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1294
1616
|
fn save(paths: &Paths, out: &Out, token: Option<String>, file: Option<PathBuf>, yes: bool) -> Outcome {
|
|
1295
1617
|
if !yes {
|
|
1296
1618
|
return Err(Fault::Usage("save needs --yes: the caller must confirm the write with the user".into()));
|