@xiaolikt/ai-vault 0.10.0 → 0.11.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 CHANGED
@@ -14,7 +14,7 @@ dependencies = [
14
14
 
15
15
  [[package]]
16
16
  name = "ai-vault"
17
- version = "0.10.0"
17
+ version = "0.11.0"
18
18
  dependencies = [
19
19
  "base64",
20
20
  "chacha20poly1305",
package/README.md CHANGED
@@ -152,12 +152,12 @@ ai-vault [--dir DIR] [--json] <command>
152
152
  | `lock --token T \| --all` | drop a token (`--all` ends every session on the machine) |
153
153
  | `list --token T` | entry metadata (name/username/URI); no passwords |
154
154
  | `get <name> [--reason R] [--answer-stdin]` | read one entry; a confirm window opens unless a grant is live |
155
- | `add --name N [--username U] [--uri U] [--notes N] [--password-stdin] [--yes]` | create/update; the password is typed in a dialog |
155
+ | `add --name N [--type TYPE] [--field NAME[=VALUE]]… [--secret NAME=VALUE]… [--username U] [--uri U] [--notes N] [--password-stdin] [--yes]` | create/update any type; a hidden field left out is typed in a dialog (`--secret` is for a host that already asked) |
156
156
  | `save --yes [--file F]` | read an array of entries as JSON and write them (the import path) |
157
157
  | `remove <name> [--yes]` | delete (quote names with spaces) |
158
158
  | `grant <name> [--minutes N]` / `revoke <name\|--all>` | a standing read grant (default 5 min, max 60); `grant` costs the master password |
159
159
  | `audit [n]` | the last n audit lines (default 30) |
160
- | `import <bitwarden.json> [--yes]` | import an unencrypted Bitwarden export |
160
+ | `import <bitwarden.json> [--yes]` | import an unencrypted Bitwarden export, every item type |
161
161
 
162
162
  The token can also come from `AI_VAULT_TOKEN`. The store directory is `--dir`,
163
163
  then `AI_VAULT_DIR`, then `~/.ai-vault`.
@@ -196,9 +196,9 @@ cannot sign an "allow".
196
196
  | Tool | What it does | Tier | Model sees the secret? |
197
197
  |---|---|---|---|
198
198
  | `vault_list` | local store metadata | read | no |
199
- | `vault_get` | read one: **local store first, Bitwarden second**; a Bitwarden hit follows `bitwarden.import` (ask / import / read once) | exec | yes, user-approved on the spot |
200
- | `vault_add` | store one; the password is typed in a dialog | write | no |
201
- | `vault_import` | copy Bitwarden logins into the local store (asks first) | write | no |
199
+ | `vault_get` | read one, any type: **local store first, Bitwarden second**; a Bitwarden hit follows `bitwarden.import` (ask / import / read once) | exec | yes, user-approved on the spot |
200
+ | `vault_add` | store one, any type; secret fields are typed in a dialog | write | no |
201
+ | `vault_import` | copy Bitwarden items of every type into the local store, field for field (asks first) | write | no |
202
202
  | `bw_list` | live Bitwarden metadata | read | no |
203
203
  | `bw_run` | run one command with `$VAULT_SECRET` in its env; output scrubbed | exec | no |
204
204
  | `bw_inject` | inject into the bash env (**pi only**) | exec | no |
@@ -213,6 +213,43 @@ whether ai-vault keeps `ENTE_CLI_VAULT_KEY` sealed for it.
213
213
  Field selector: `password` (default) · `totp` (seed) · `code` (rotating code) ·
214
214
  `notes` · `field:<custom field name>`.
215
215
 
216
+ ### Item types
217
+
218
+ ai-vault stores the same item types Bitwarden does, with the same field names,
219
+ so an import is a copy and a manual entry is the same shape:
220
+
221
+ | Type | `--type` | Its own fields (`data`) | Secret field |
222
+ |---|---|---|---|
223
+ | Login | `login` (default) | `username`, `password`, `totp` + `uris` | `password` |
224
+ | Secure note | `note` | none — the content is `notes` | — |
225
+ | Card | `card` | `cardholderName`, `brand`, `number`, `expMonth`, `expYear`, `code` | `number`, `code` |
226
+ | Identity | `identity` | `title`, `firstName`, `middleName`, `lastName`, `address1–3`, `city`, `state`, `postalCode`, `country`, `company`, `email`, `phone`, `ssn`, `username`, `passportNumber`, `licenseNumber` | `ssn`, document numbers |
227
+ | SSH key | `sshkey` | `privateKey`, `publicKey`, `keyFingerprint` | `privateKey` |
228
+ | Bank account | `bankaccount` | `bankName`, `nameOnAccount`, `accountType`, `accountNumber`, `routingNumber`, `branchNumber`, `pin`, `swiftCode`, `iban`, `bankContactPhone` | `accountNumber`, `routingNumber`, `pin` |
229
+ | Driver's licence | `driverslicense` | `firstName`, `middleName`, `lastName`, `dateOfBirth`, `licenseNumber`, `issuingCountry`, `issuingState`, `issueDate`, `expirationDate`, `issuingAuthority`, `licenseClass` | `licenseNumber` |
230
+ | Passport | `passport` | `surname`, `givenName`, `dateOfBirth`, `sex`, `birthPlace`, `nationality`, `issuingCountry`, `passportNumber`, `passportType`, `nationalIdentificationNumber`, `issuingAuthority`, `issueDate`, `expirationDate` | `passportNumber`, `nationalIdentificationNumber` |
231
+
232
+ The last three are behind Bitwarden's "new item types" flag; the CLI stores
233
+ them the same way. Every type also carries `notes` and custom `fields[]`
234
+ (`type`: 0 text · 1 hidden · 2 boolean · 3 linked, as in Bitwarden). A hidden
235
+ custom field is treated as a secret everywhere.
236
+
237
+ ```bash
238
+ # by hand: non-secret fields on the line, the secret typed in a window
239
+ ai-vault add --name Visa --type card --field cardholderName="Li Jun" --field brand=Visa --field expYear=2029
240
+ ai-vault add --name "Wifi" --type note --notes "guest network: …"
241
+ ai-vault add --name server --type sshkey --field publicKey="ssh-ed25519 AAAA" # private key typed
242
+ ```
243
+
244
+ `list` shows the type and the non-secret fields (cardholder, brand, expiry,
245
+ a person's name, the key's fingerprint…); it never shows a password, card
246
+ number or code, private key, PIN, account or document number, a hidden custom
247
+ field, a TOTP seed, or a secure note's body. `get` returns the whole entry.
248
+
249
+ The `vault_add` tool takes `type` and `fields` the same way. A secret field the
250
+ model fills in itself is refused: those are typed by the user in a dialog, one
251
+ window per field.
252
+
216
253
  ### Lookup order: local first, Bitwarden as fallback
217
254
 
218
255
  `vault_get` asks `ai-vault` (the store this machine shares) first and only
@@ -287,13 +324,14 @@ policy goes back to `session`, and `/bw lock` clears it too.
287
324
 
288
325
  ```
289
326
  /vault init create the local store (dialog sets the master password)
327
+ /vault add card:Visa brand=Visa code type:name, fields on the line, a bare field typed in a dialog
290
328
  /vault unlock | lock unlock / lock this session
291
329
  /vault mode [never|time|session] show / switch the unlock policy (switching needs the password)
292
330
  /vault settings [key value] show / change settings (bitwarden.*, ente.*)
293
331
  /vault ente-key save Ente's ENTE_CLI_VAULT_KEY (no keychain, no login)
294
332
  /vault status state, expiry, grants left
295
333
  /vault list entry metadata
296
- /vault add [name] add (username and password typed in a dialog)
334
+ /vault add [type:]name [field=value|field]… add any type; a bare field is typed in a dialog
297
335
  /vault remove <name> delete (quote names like "GitHub (2)")
298
336
  /vault grant <name> [minutes] a standing read grant (needs the master password)
299
337
  /vault revoke <name|all> revoke grants
package/README.zh.md CHANGED
@@ -138,7 +138,7 @@ ai-vault [--dir DIR] [--json] <命令>
138
138
  | `lock --token T \| --all` | 丢掉令牌(`--all` 清空本机所有会话) |
139
139
  | `list --token T` | 条目元数据(名称/用户名/URI),没有密码 |
140
140
  | `get <名字> [--reason R] [--answer-stdin]` | 读一条;没有授权时先弹确认窗 |
141
- | `add --name N [--username U] [--uri U] [--notes N] [--password-stdin] [--yes]` | 新增/更新;密码由弹窗输入 |
141
+ | `add --name N [--type TYPE] [--field NAME[=VALUE]]… [--secret NAME=VALUE]… [--username U] [--uri U] [--notes N] [--password-stdin] [--yes]` | 新增/更新任意类型;没给的隐藏字段弹窗输(`--secret` 给已经问过用户的宿主用) |
142
142
  | `save --yes [--file F]` | 从 stdin 读一组条目 JSON,批量写入(导入用) |
143
143
  | `remove <名字> [--yes]` | 删除(带空格的名称加引号) |
144
144
  | `grant <名字> [--minutes N]` / `revoke <名字\|--all>` | 手动给/撤读授权(默认 5 分钟,上限 60);`grant` 要主密码 |
@@ -176,9 +176,9 @@ ai-vault get <条目> --token <T> --answer-stdin --approval <hex> <<< 'y'
176
176
  | 工具 | 作用 | 等级 | 模型看到密码? |
177
177
  |---|---|---|---|
178
178
  | `vault_list` | 本地库元数据 | read | 否 |
179
- | `vault_get` | 读一条:**先本地库,再 Bitwarden**;命中后按 `bitwarden.import` 处理(问 / 直接导入 / 只读一次) | exec | 是,用户当场允许 |
180
- | `vault_add` | 存一条;密码在弹窗里输入 | write | 否 |
181
- | `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | write | 否 |
179
+ | `vault_get` | 读一条,任意类型:**先本地库,再 Bitwarden**;命中后按 `bitwarden.import` 处理 | exec | 是,用户当场允许 |
180
+ | `vault_add` | 存一条,任意类型;秘密字段在弹窗里输 | write | 否 |
181
+ | `vault_import` | 把 Bitwarden 每种类型的条目按字段抄进本地库(先确认) | write | 否 |
182
182
  | `bw_list` | 查在线 Bitwarden 元数据 | read | 否 |
183
183
  | `bw_run` | 用 `$VAULT_SECRET` 跑一条命令,输出擦洗 | exec | 否 |
184
184
  | `bw_inject` | 注入 bash 环境(**仅 pi**) | exec | 否 |
@@ -191,6 +191,34 @@ Ente 的会话由 `ente` 自己管(登录一次);`ente.unlock` 只决定
191
191
 
192
192
  字段选择:`password`(默认)· `totp`(种子)· `code`(动态验证码)· `notes` · `field:<自定义字段名>`。
193
193
 
194
+ ### 条目类型
195
+
196
+ ai-vault 存的和 Bitwarden 一样的条目类型、一样的字段名,所以导入就是复制,手动录入也是同一个形状:
197
+
198
+ | 类型 | `--type` | 自己的字段(`data`) | 秘密字段 |
199
+ |---|---|---|---|
200
+ | 登录 | `login`(默认) | `username`、`password`、`totp` + `uris` | `password` |
201
+ | 安全笔记 | `note` | 没有——内容就是 `notes` | — |
202
+ | 银行卡 | `card` | `cardholderName`、`brand`、`number`、`expMonth`、`expYear`、`code` | `number`、`code` |
203
+ | 身份 | `identity` | `title`、`firstName`、`middleName`、`lastName`、`address1–3`、`city`、`state`、`postalCode`、`country`、`company`、`email`、`phone`、`ssn`、`username`、`passportNumber`、`licenseNumber` | `ssn`、证件号 |
204
+ | SSH 密钥 | `sshkey` | `privateKey`、`publicKey`、`keyFingerprint` | `privateKey` |
205
+ | 银行账户 | `bankaccount` | `bankName`、`nameOnAccount`、`accountType`、`accountNumber`、`routingNumber`、`branchNumber`、`pin`、`swiftCode`、`iban`、`bankContactPhone` | `accountNumber`、`routingNumber`、`pin` |
206
+ | 驾照 | `driverslicense` | `firstName`、`middleName`、`lastName`、`dateOfBirth`、`licenseNumber`、`issuingCountry`、`issuingState`、`issueDate`、`expirationDate`、`issuingAuthority`、`licenseClass` | `licenseNumber` |
207
+ | 护照 | `passport` | `surname`、`givenName`、`dateOfBirth`、`sex`、`birthPlace`、`nationality`、`issuingCountry`、`passportNumber`、`passportType`、`nationalIdentificationNumber`、`issuingAuthority`、`issueDate`、`expirationDate` | `passportNumber`、`nationalIdentificationNumber` |
208
+
209
+ 后三种在 Bitwarden 的「新条目类型」开关后面,CLI 一视同仁地存。每种类型都还带 `notes` 和自定义 `fields[]`(`type`:0 文本 · 1 隐藏 · 2 布尔 · 3 链接,和 Bitwarden 一致)。隐藏的自定义字段在所有地方都按秘密处理。
210
+
211
+ ```bash
212
+ # 手动录入:非秘密字段写在命令行,秘密在弹窗里输
213
+ ai-vault add --name Visa --type card --field cardholderName="李军" --field brand=Visa --field expYear=2029
214
+ ai-vault add --name Wifi --type note --notes "访客网络:…"
215
+ ai-vault add --name server --type sshkey --field publicKey="ssh-ed25519 AAAA" # 私钥弹窗输
216
+ ```
217
+
218
+ `list` 显示类型和非秘密字段(持卡人、品牌、有效期、人名、密钥指纹……);绝不显示密码、卡号和 CVV、私钥、PIN、账号和证件号、隐藏的自定义字段、TOTP 种子、安全笔记的正文。`get` 返回整条。
219
+
220
+ `vault_add` 工具同样接受 `type` 和 `fields`。模型自己填秘密字段会被拒绝:那些由用户在弹窗里输,一个字段一个窗口。
221
+
194
222
  ### 查询顺序:本地优先,Bitwarden 兜底
195
223
 
196
224
  `vault_get` 先问 `ai-vault`(这台机器共用的库),只有本地没有才去搜 Bitwarden:
@@ -253,6 +281,7 @@ ai-vault settings bitwarden.hours 24
253
281
 
254
282
  ```
255
283
  /vault init 创建本地库(弹窗设主密码)
284
+ /vault add card:Visa brand=Visa code 类型:名称,字段写在行里,只写字段名的弹窗输
256
285
  /vault unlock | lock 解锁 / 锁定本会话
257
286
  /vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)
258
287
  /vault settings [键 值] 查看/修改设置(bitwarden.* 也在这里)
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ai-vault"
3
- version = "0.10.0"
3
+ version = "0.11.0"
4
4
  edition = "2021"
5
5
  description = "Machine-wide encrypted secret store shared by AI coding agents"
6
6
  license = "MIT"
@@ -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::{self, Draft, Item};
19
+ use crate::store::{Draft, Item, ItemType, self};
20
20
  use crate::{audit, store::ItemSummary};
21
21
 
22
22
  #[derive(Parser, Debug)]
@@ -137,17 +137,29 @@ enum Cmd {
137
137
  #[arg(long, value_name = "HEX")]
138
138
  approval: Option<String>,
139
139
  },
140
- /// Create or update an entry; the password is typed in a dialog
140
+ /// Create or update an entry of any type; the secret is typed in a dialog
141
141
  Add {
142
142
  #[arg(long)]
143
143
  name: String,
144
+ /// login (default) | note | card | identity | sshkey | bankaccount | driverslicense | passport
145
+ #[arg(long, value_name = "TYPE")]
146
+ r#type: Option<String>,
144
147
  #[arg(long)]
145
148
  username: Option<String>,
146
149
  #[arg(long)]
147
150
  uri: Option<String>,
148
151
  #[arg(long)]
149
152
  notes: Option<String>,
150
- /// Read the password from stdin instead of a dialog
153
+ /// A field of the type, NAME=VALUE; repeatable. A field given as NAME
154
+ /// alone, or any hidden field left out, is typed in a dialog (or sent
155
+ /// on stdin for the primary one with --password-stdin).
156
+ #[arg(long = "field", value_name = "NAME[=VALUE]")]
157
+ fields: Vec<String>,
158
+ /// A hidden field supplied by a host that already asked the user for
159
+ /// it, NAME=VALUE; repeatable. Never printed, never in a window.
160
+ #[arg(long = "secret", value_name = "NAME=VALUE")]
161
+ secrets: Vec<String>,
162
+ /// Read the secret from stdin instead of a dialog
151
163
  #[arg(long)]
152
164
  password_stdin: bool,
153
165
  /// Skip the "save this?" confirm window (the user already approved)
@@ -218,6 +230,8 @@ enum Fault {
218
230
  Usage(String),
219
231
  /// No desktop window could be opened; the host must supply the value.
220
232
  NeedsUi(&'static str),
233
+ /// The same, for one named hidden field of a typed entry.
234
+ NeedsUiField(String),
221
235
  Denied(String),
222
236
  Auth(String),
223
237
  }
@@ -227,7 +241,7 @@ impl Fault {
227
241
  match self {
228
242
  Fault::Error(_) => 1,
229
243
  Fault::Usage(_) => 2,
230
- Fault::NeedsUi(_) => 3,
244
+ Fault::NeedsUi(_) | Fault::NeedsUiField(_) => 3,
231
245
  Fault::Denied(_) => 4,
232
246
  Fault::Auth(_) => 5,
233
247
  }
@@ -266,6 +280,11 @@ pub fn run() -> i32 {
266
280
  eprintln!("needs-ui: {step}");
267
281
  eprintln!("no desktop window is available; the host must supply this value");
268
282
  }
283
+ Fault::NeedsUiField(field) => {
284
+ eprintln!("needs-ui: password field={field}");
285
+ eprintln!("no desktop window is available; the host must supply this value");
286
+ }
287
+ // (NeedsUi with a detail is printed by `needs_ui` below)
269
288
  Fault::Usage(message) => eprintln!("ai-vault: {message}"),
270
289
  Fault::Error(message) | Fault::Denied(message) | Fault::Auth(message) => {
271
290
  eprintln!("ai-vault: {message}")
@@ -337,8 +356,8 @@ fn dispatch(cmd: Cmd, paths: &Paths, json: bool) -> Outcome {
337
356
  Cmd::Get { name, token, reason, answer_stdin, approval } => {
338
357
  get(paths, &out, token, &name, reason.as_deref(), answer_stdin, approval)
339
358
  }
340
- Cmd::Add { name, username, uri, notes, password_stdin, yes, token } => {
341
- add(paths, &out, token, AddRequest { name, username, uri, notes, password_stdin, yes })
359
+ Cmd::Add { name, r#type, username, uri, notes, fields, secrets, password_stdin, yes, token } => {
360
+ add(paths, &out, token, AddRequest { name, r#type, username, uri, notes, fields, secrets, password_stdin, yes })
342
361
  }
343
362
  Cmd::Save { token, file, yes } => save(paths, &out, token, file, yes),
344
363
  Cmd::Remove { name, yes, token } => remove(paths, &out, token, &name, yes),
@@ -455,11 +474,17 @@ fn ask_password(title: &str, label: &str) -> Result<String, Fault> {
455
474
  }
456
475
  }
457
476
 
458
- fn ask_text(title: &str, label: &str) -> Result<String, Fault> {
459
- match dialog::prompt_text(title, label) {
477
+ /// The same, naming the field on the `needs-ui` line so a host can title its
478
+ /// own dialog and send the value back as `--secret NAME=VALUE`.
479
+ /// The same, but when no window can open the `needs-ui` line names the field,
480
+ /// so a host can title its own dialog and send the answer back as `--secret`.
481
+ /// The field is reported in the error's text, which the host reads after the
482
+ /// `needs-ui: password` line.
483
+ fn ask_field_password(field: &str, title: &str, label: &str) -> Result<String, Fault> {
484
+ match dialog::prompt_secret(title, label) {
460
485
  Answer::Value(value) => Ok(value),
461
- Answer::Cancelled => Err(Fault::Denied("cancelled".into())),
462
- Answer::NoUi => Err(Fault::NeedsUi("text")),
486
+ Answer::Cancelled => Err(Fault::Denied("cancelled: no password entered".into())),
487
+ Answer::NoUi => Err(Fault::NeedsUiField(field.to_string())),
463
488
  }
464
489
  }
465
490
 
@@ -502,7 +527,7 @@ fn signing_key(paths: &Paths) -> Result<Option<String>, String> {
502
527
  /// and is treated like a human caller until it has a secret to sign with.
503
528
  /// This keeps a half-configured host from getting a session it can neither
504
529
  /// verify nor relay for.
505
- fn kind_label(kind: Kind) -> &'static str {
530
+ fn secret_kind_label(kind: Kind) -> &'static str {
506
531
  match kind {
507
532
  Kind::Bitwarden => "bitwarden",
508
533
  Kind::Ente => "ente",
@@ -964,9 +989,9 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
964
989
  match action.trim() {
965
990
  "" | "get" => {
966
991
  let stored = sealed::load(paths, kind)?
967
- .ok_or_else(|| Fault::Auth(format!("no persisted {} secret — save one first", kind_label(kind))))?;
992
+ .ok_or_else(|| Fault::Auth(format!("no persisted {} secret — save one first", secret_kind_label(kind))))?;
968
993
  let key = sealed::key(paths, kind)?
969
- .ok_or_else(|| Fault::Auth(format!("no persisted {} secret", kind_label(kind))))?;
994
+ .ok_or_else(|| Fault::Auth(format!("no persisted {} secret", secret_kind_label(kind))))?;
970
995
  out.value(
971
996
  json!({ "ok": true, "key": key, "savedAt": stored.saved_at, "expiresAt": stored.expires_at }),
972
997
  || key,
@@ -979,7 +1004,7 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
979
1004
  return Err(Fault::Usage("bw-session put expects the session key on stdin".into()));
980
1005
  }
981
1006
  let expires_at = sealed::save(paths, kind, &key)?;
982
- audit::append(&paths.audit(), "cli", "sealed", None, Some(kind_label(kind)));
1007
+ audit::append(&paths.audit(), "cli", "sealed", None, Some(secret_kind_label(kind)));
983
1008
  out.value(json!({ "ok": true, "expiresAt": expires_at }), || {
984
1009
  match expires_at {
985
1010
  Some(at) => format!("saved (expires in {} min)", ((at - session::now_ms()) / 60_000).max(0)),
@@ -990,7 +1015,7 @@ fn sealed_session(paths: &Paths, out: &Out, kind: Kind, action: &str) -> Outcome
990
1015
  }
991
1016
  "clear" | "delete" => {
992
1017
  let removed = sealed::clear(paths, kind);
993
- audit::append(&paths.audit(), "cli", "sealed", None, Some(kind_label(kind)));
1018
+ audit::append(&paths.audit(), "cli", "sealed", None, Some(secret_kind_label(kind)));
994
1019
  out.value(json!({ "ok": true, "removed": removed }), || {
995
1020
  if removed { "cleared".to_string() } else { "nothing stored".to_string() }
996
1021
  });
@@ -1090,7 +1115,15 @@ fn list(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
1090
1115
  }
1091
1116
  items
1092
1117
  .iter()
1093
- .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()))
1118
+ .map(|i| {
1119
+ format!(
1120
+ "{}\t{}\t{}\t{}",
1121
+ i.name,
1122
+ kind_label(i.r#type),
1123
+ i.username.clone().unwrap_or_default(),
1124
+ i.uris.as_ref().and_then(|u| u.first()).cloned().unwrap_or_default()
1125
+ )
1126
+ })
1094
1127
  .collect::<Vec<_>>()
1095
1128
  .join("\n")
1096
1129
  });
@@ -1128,7 +1161,7 @@ fn get(
1128
1161
  let message = format!(
1129
1162
  "{} {}\n{} {}\n{} {}\n\n{}",
1130
1163
  tr("Entry:", "条目:"),
1131
- dialog::for_dialog(&item.name, 80),
1164
+ format!("{} ({})", dialog::for_dialog(&item.name, 80), kind_label(item.r#type)),
1132
1165
  tr("Requester:", "请求方:"),
1133
1166
  dialog::for_dialog(&session.requester, 40),
1134
1167
  tr("Reason:", "原因:"),
@@ -1196,46 +1229,127 @@ fn get(
1196
1229
 
1197
1230
  struct AddRequest {
1198
1231
  name: String,
1232
+ r#type: Option<String>,
1199
1233
  username: Option<String>,
1200
1234
  uri: Option<String>,
1201
1235
  notes: Option<String>,
1236
+ fields: Vec<String>,
1237
+ secrets: Vec<String>,
1202
1238
  password_stdin: bool,
1203
1239
  yes: bool,
1204
1240
  }
1205
1241
 
1242
+ /// Parse a type name the way a human writes it: login, note, secure-note,
1243
+ /// ssh key, "SSH key", drivers licence …
1244
+ fn parse_item_type(raw: &str) -> Option<ItemType> {
1245
+ let key: String = raw.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase();
1246
+ Some(match key.as_str() {
1247
+ "login" | "password" | "" => ItemType::Login,
1248
+ "note" | "securenote" => ItemType::SecureNote,
1249
+ "card" | "creditcard" => ItemType::Card,
1250
+ "identity" | "person" => ItemType::Identity,
1251
+ "sshkey" | "ssh" | "key" => ItemType::SshKey,
1252
+ "bankaccount" | "bank" => ItemType::BankAccount,
1253
+ "driverslicense" | "driverlicense" | "license" | "drivinglicence" => ItemType::DriversLicense,
1254
+ "passport" => ItemType::Passport,
1255
+ _ => return None,
1256
+ })
1257
+ }
1258
+
1206
1259
  fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outcome {
1207
1260
  let mut session = load_session(paths, token.as_deref())?;
1208
1261
  let name = req.name.trim().to_string();
1209
1262
  if name.is_empty() {
1210
1263
  return Err(Fault::Usage("an entry needs a name".into()));
1211
1264
  }
1265
+ let kind = match req.r#type.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
1266
+ None => ItemType::Login,
1267
+ Some(raw) => parse_item_type(raw).ok_or_else(|| {
1268
+ Fault::Usage(format!(
1269
+ "unknown type \"{raw}\" — login, note, card, identity, sshkey, bankaccount, driverslicense, passport"
1270
+ ))
1271
+ })?,
1272
+ };
1212
1273
  let store = open_store(paths)?;
1213
1274
  let items = items_with(&session, &store)?;
1214
1275
  let existing = store::find(&items, &name).cloned();
1276
+ // Updating an entry of another type replaces its data block: say so in the window.
1277
+ let type_changes = existing.as_ref().is_some_and(|item| item.r#type != kind);
1278
+
1279
+ // --field NAME=VALUE pairs, by the type's own field names.
1280
+ let mut data: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
1281
+ let mut to_type: Vec<String> = Vec::new();
1282
+ for raw in &req.fields {
1283
+ let (field, value) = match raw.split_once('=') {
1284
+ Some((f, v)) => (f.trim().to_string(), Some(v.to_string())),
1285
+ None => (raw.trim().to_string(), None),
1286
+ };
1287
+ let field = resolve_field_name(kind, &field)
1288
+ .ok_or_else(|| Fault::Usage(format!("\"{field}\" is not a field of a {}", kind_label(kind))))?;
1289
+ match value {
1290
+ Some(v) => {
1291
+ data.insert(field, serde_json::Value::String(v));
1292
+ }
1293
+ None => to_type.push(field),
1294
+ }
1295
+ }
1296
+ // Host-supplied hidden fields (the host asked the user in its own UI).
1297
+ for raw in &req.secrets {
1298
+ let (field, value) = raw.split_once('=').ok_or_else(|| Fault::Usage("--secret expects NAME=VALUE".into()))?;
1299
+ let field = resolve_field_name(kind, field.trim())
1300
+ .ok_or_else(|| Fault::Usage(format!("\"{}\" is not a field of a {}", field.trim(), kind_label(kind))))?;
1301
+ if !is_secret_field(kind, &field) {
1302
+ return Err(Fault::Usage(format!("--secret is for hidden fields; \"{field}\" can go in --field")));
1303
+ }
1304
+ data.insert(field, serde_json::Value::String(value.to_string()));
1305
+ }
1306
+ // The conventional flags feed the login fields and the shared notes.
1307
+ if kind == ItemType::Login {
1308
+ if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
1309
+ data.insert("username".into(), serde_json::Value::String(user.to_string()));
1310
+ }
1311
+ }
1312
+ let notes = req.notes.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
1215
1313
 
1216
1314
  if !req.yes {
1217
1315
  let mut meta = Vec::new();
1316
+ let shown = dialog::for_dialog(&name, 80);
1317
+ let action = match &existing {
1318
+ Some(_) if type_changes => tr_owned(
1319
+ format!("Replace \"{shown}\" with a {} entry.", kind_label(kind)),
1320
+ format!("把「{shown}」改成{}条目。", kind_label(kind)),
1321
+ ),
1322
+ Some(_) => tr_owned(format!("Update the existing entry \"{shown}\"."), format!("更新已有条目「{shown}」。")),
1323
+ None => tr_owned(format!("Create a {} entry \"{shown}\".", kind_label(kind)), format!("新建{}条目「{shown}」。", kind_label(kind))),
1324
+ };
1325
+ for (field, value) in &data {
1326
+ let secret = is_secret_field(kind, field);
1327
+ meta.push(format!(
1328
+ "{} {}",
1329
+ field,
1330
+ if secret { "••••".to_string() } else { dialog::for_dialog(value.as_str().unwrap_or(""), 120) }
1331
+ ));
1332
+ }
1333
+ for field in &to_type {
1334
+ meta.push(format!("{field} ••••"));
1335
+ }
1218
1336
  if let Some(user) = req.username.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
1219
- meta.push(format!("{} {}", tr("Username:", "用户名:"), dialog::for_dialog(user, 60)));
1337
+ if kind != ItemType::Login {
1338
+ meta.push(format!("{} {}", tr("Username:", "用户名:"), dialog::for_dialog(user, 60)));
1339
+ }
1220
1340
  }
1221
1341
  if let Some(uri) = req.uri.as_deref().map(str::trim).filter(|u| !u.is_empty()) {
1222
1342
  meta.push(format!("URI: {}", dialog::for_dialog(uri, 120)));
1223
1343
  }
1224
- if let Some(notes) = req.notes.as_deref().map(str::trim).filter(|n| !n.is_empty()) {
1344
+ if let Some(notes) = notes.as_deref() {
1225
1345
  meta.push(format!("{} {}", tr("Notes:", "备注:"), dialog::for_dialog(notes, 120)));
1226
1346
  }
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
1347
  let message = format!(
1234
1348
  "{action}{}\n{}",
1235
1349
  if meta.is_empty() { String::new() } else { format!("\n{}", meta.join("\n")) },
1236
1350
  tr(
1237
- "A window opens next for you to type the password. It never enters the conversation.",
1238
- "下一步会弹出窗口,由你输入密码。密码不会进入对话。"
1351
+ "A window opens next for each hidden field. Nothing enters the conversation.",
1352
+ "接下来每个隐藏字段弹一个窗口。密码不会进入对话。"
1239
1353
  )
1240
1354
  );
1241
1355
  match dialog::confirm(tr("ai-vault · save to local store", "ai-vault · 保存到本地库"), &message) {
@@ -1245,52 +1359,134 @@ fn add(paths: &Paths, out: &Out, token: Option<String>, req: AddRequest) -> Outc
1245
1359
  }
1246
1360
  }
1247
1361
 
1248
- let username = match req.username {
1249
- Some(user) => user,
1250
- None => {
1251
- let hint = if existing.as_ref().and_then(|i| i.username.as_ref()).is_some() {
1252
- tr("username (leave blank to keep)", "用户名(留空保持不变)")
1253
- } else {
1254
- tr("username (optional)", "用户名(可留空)")
1255
- };
1256
- ask_text(&format!("ai-vault · {name}"), hint)?
1362
+ // Hidden fields: typed in a dialog (or read from stdin for the primary one).
1363
+ // On an update, a secret the caller did not mention is left as stored; only
1364
+ // a new entry (or a type change) needs every secret typed.
1365
+ let primary = kind.primary_field();
1366
+ let fresh = existing.as_ref().map_or(true, |item| item.r#type != kind);
1367
+ let mut secret_fields: Vec<String> = to_type;
1368
+ if fresh {
1369
+ if let Some(field) = primary {
1370
+ if !data.contains_key(field) {
1371
+ secret_fields.push(field.to_string());
1372
+ }
1257
1373
  }
1258
- };
1259
- let password = if req.password_stdin {
1260
- read_password()?
1261
- } else {
1262
- ask_password(tr("ai-vault · password", "ai-vault · 密码"), &name)?
1263
- };
1264
- if password.is_empty() {
1265
- return Err(Fault::Denied("cancelled: no password entered".into()));
1374
+ } else if let Some(item) = &existing {
1375
+ // Carry over the stored data block so `apply` does not read the absent
1376
+ // fields as "clear"; the draft's own values still win.
1377
+ for (field, value) in item.data.clone().unwrap_or_default() {
1378
+ data.entry(field).or_insert(value);
1379
+ }
1380
+ }
1381
+ for field in secret_fields {
1382
+ let password = if req.password_stdin && Some(field.as_str()) == primary {
1383
+ read_password()?
1384
+ } else {
1385
+ ask_field_password(&field, tr("ai-vault · password", "ai-vault · 密码"), &format!("{name} · {field}"))?
1386
+ };
1387
+ if password.is_empty() {
1388
+ return Err(Fault::Denied("cancelled: no password entered".into()));
1389
+ }
1390
+ data.insert(field, serde_json::Value::String(password));
1391
+ }
1392
+ if kind == ItemType::SecureNote && notes.is_none() && data.is_empty() {
1393
+ // A secure note is its notes; a dialog for the body when none was given.
1394
+ let body = match dialog::prompt_text(tr("ai-vault · note", "ai-vault · 备注"), tr("the note's contents", "备注内容")) {
1395
+ Answer::Value(text) => text,
1396
+ Answer::Cancelled => return Err(Fault::Denied("cancelled".into())),
1397
+ Answer::NoUi => return Err(Fault::NeedsUi("text")),
1398
+ };
1399
+ if body.trim().is_empty() {
1400
+ return Err(Fault::Usage("a note needs contents (--notes)".into()));
1401
+ }
1402
+ let notes = Some(body);
1403
+ return finish_add(paths, out, &mut session, Draft {
1404
+ name: name.clone(),
1405
+ r#type: kind,
1406
+ notes,
1407
+ data: None,
1408
+ ..Default::default()
1409
+ }, &name);
1266
1410
  }
1267
1411
 
1268
- let user = username.trim().to_string();
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());
1412
+ let uris = req.uri.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()).map(|u| vec![u]);
1271
1413
  let draft = Draft {
1272
- id: None,
1273
1414
  name: name.clone(),
1274
- username: if user.is_empty() { None } else { Some(user) },
1275
- password,
1276
- uris: uri.map(|u| vec![u]),
1415
+ r#type: kind,
1416
+ username: if kind == ItemType::Login { req.username.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()) } else { None },
1417
+ password: String::new(),
1418
+ uris,
1419
+ data: if data.is_empty() { None } else { Some(data) },
1277
1420
  notes,
1278
- source: None,
1421
+ ..Default::default()
1279
1422
  };
1423
+ finish_add(paths, out, &mut session, draft, &name)
1424
+ }
1425
+
1426
+ fn finish_add(paths: &Paths, out: &Out, session: &mut Session, draft: Draft, name: &str) -> Outcome {
1280
1427
  let mut inserted = false;
1281
- mutate(paths, &session, |items, now| {
1428
+ let kind = draft.r#type;
1429
+ mutate(paths, session, |items, now| {
1282
1430
  inserted = store::apply(items, draft, now);
1283
1431
  Ok(())
1284
1432
  })?;
1285
1433
  session.last_active = session::now_ms();
1286
- persist(paths, &session);
1287
- audit::append(&paths.audit(), &session.requester, "add", Some(&name), None);
1288
- out.value(json!({ "ok": true, "item": name, "created": inserted }), || {
1289
- format!("saved \"{name}\" (password entered in the dialog, not shown)")
1434
+ persist(paths, session);
1435
+ audit::append(&paths.audit(), &session.requester, "add", Some(name), Some(kind_label(kind)));
1436
+ let mut value = json!({ "ok": true, "item": name, "type": kind_label(kind), "created": inserted });
1437
+ if let Some(record) = value.as_object_mut() {
1438
+ record.insert("fields".into(), json!(kind.fields()));
1439
+ }
1440
+ out.value(value, || {
1441
+ format!(
1442
+ "saved \"{name}\" as a {} (hidden fields typed in the dialog, not shown)",
1443
+ kind_label(kind)
1444
+ )
1290
1445
  });
1291
1446
  Ok(())
1292
1447
  }
1293
1448
 
1449
+ /// A type's field by the name a human typed (case- and separator-insensitive).
1450
+ fn resolve_field_name(kind: ItemType, raw: &str) -> Option<String> {
1451
+ let key: String = raw.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase();
1452
+ kind.fields()
1453
+ .iter()
1454
+ .find(|f| f.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase() == key)
1455
+ .map(|f| f.to_string())
1456
+ }
1457
+
1458
+ /// Fields whose value must never be printed in a window or in `list`.
1459
+ pub(crate) fn is_secret_field(kind: ItemType, field: &str) -> bool {
1460
+ matches!(
1461
+ (kind, field),
1462
+ (_, "password")
1463
+ | (_, "privateKey")
1464
+ | (ItemType::Card, "code")
1465
+ | (ItemType::Card, "number")
1466
+ | (ItemType::BankAccount, "pin")
1467
+ | (ItemType::BankAccount, "accountNumber")
1468
+ | (ItemType::BankAccount, "routingNumber")
1469
+ | (_, "ssn")
1470
+ | (_, "licenseNumber")
1471
+ | (_, "passportNumber")
1472
+ | (ItemType::Passport, "nationalIdentificationNumber")
1473
+ | (_, "totp")
1474
+ )
1475
+ }
1476
+
1477
+ fn kind_label(kind: ItemType) -> &'static str {
1478
+ match kind {
1479
+ ItemType::Login => "login",
1480
+ ItemType::SecureNote => "note",
1481
+ ItemType::Card => "card",
1482
+ ItemType::Identity => "identity",
1483
+ ItemType::SshKey => "SSH key",
1484
+ ItemType::BankAccount => "bank account",
1485
+ ItemType::DriversLicense => "driver's licence",
1486
+ ItemType::Passport => "passport",
1487
+ }
1488
+ }
1489
+
1294
1490
  fn save(paths: &Paths, out: &Out, token: Option<String>, file: Option<PathBuf>, yes: bool) -> Outcome {
1295
1491
  if !yes {
1296
1492
  return Err(Fault::Usage("save needs --yes: the caller must confirm the write with the user".into()));