@xiaolikt/ai-vault 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Cargo.lock CHANGED
@@ -14,7 +14,7 @@ dependencies = [
14
14
 
15
15
  [[package]]
16
16
  name = "ai-vault"
17
- version = "0.14.0"
17
+ version = "0.14.1"
18
18
  dependencies = [
19
19
  "base64",
20
20
  "chacha20poly1305",
package/README.md CHANGED
@@ -330,10 +330,18 @@ or `time` towards `never` costs the master password; moving towards `every`
330
330
  is free. Switching to `every` deletes every live token of the store at once.
331
331
 
332
332
  **Why one unlock serves every tab.** Every pi/omp process on the machine
333
- shares one store-wide host secret (`~/.ai-vault/.host`, 0600), so a session
334
- opened in one process is usable in the next. The secret is protected by
335
- exactly what protects the store and its wrap key, the user's home directory;
336
- a token found on disk is still refused without it.
333
+ shares one store-wide host secret (`~/.ai-vault/.host`, 0600). A call that
334
+ comes without a token looks for a live session of this store that it can
335
+ verify under that secret, and — in `time` mode — **adopts the unlock**: it
336
+ gets a session of its own under the same key (its own token, no grants), so
337
+ the password is not asked again while any tab still holds an unlock, yet a
338
+ subagent still approves its own reads and `/vault lock` still locks only the
339
+ tab that ran it. A process without the secret — a stolen token, another
340
+ user — is refused; a human at a terminal (the wrap key) cannot adopt a
341
+ host's session either. The secret is protected by exactly what protects the
342
+ store and its wrap key, the user's home directory.
343
+
344
+ In `every` mode there is nothing to adopt: every call brings its password.
337
345
 
338
346
  **`every` and the plaintext hint.** The settings live inside the ciphertext,
339
347
  but the CLI must know to *ask* before it can read them. So the file header
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ai-vault"
3
- version = "0.14.0"
3
+ version = "0.14.1"
4
4
  edition = "2021"
5
5
  description = "Machine-wide encrypted secret store shared by AI coding agents"
6
6
  license = "MIT"
@@ -479,6 +479,21 @@ fn master_password_for_call() -> Result<zeroize::Zeroizing<String>, Fault> {
479
479
  }
480
480
  }
481
481
 
482
+ /// The password for a verification: the environment a host passed, then
483
+ /// stdin, then a window. A host that passed nothing is told to ask.
484
+ fn master_password_from(why: &str, password_stdin: bool) -> Result<zeroize::Zeroizing<String>, Fault> {
485
+ if let Some(PasswordSource::Env(password)) = PASSWORD_SOURCE.get() {
486
+ return Ok(zeroize::Zeroizing::new(password.clone()));
487
+ }
488
+ if password_stdin {
489
+ return read_password().map(zeroize::Zeroizing::new);
490
+ }
491
+ if is_host() {
492
+ return Err(Fault::NeedsUi("password"));
493
+ }
494
+ ask_password(tr("ai-vault · master password", "ai-vault · 主密码"), why).map(zeroize::Zeroizing::new)
495
+ }
496
+
482
497
  fn read_password() -> Result<String, Fault> {
483
498
  let line = read_line()?;
484
499
  let password = line.trim_end_matches(['\r', '\n']).to_string();
@@ -643,6 +658,33 @@ fn load_session(paths: &Paths, token: Option<&str>) -> Result<Session, Fault> {
643
658
  if let Some(auto) = auto_session(paths) {
644
659
  return Ok(auto);
645
660
  }
661
+ // `time` mode: a token another process opened for this store is as good
662
+ // as one this process opened. They share the store-wide host secret, so
663
+ // the newest live one verifies here too — which is the whole point of
664
+ // `time`: a second herdr tab, a subagent or a --restore picks up the
665
+ // unlock that already exists instead of asking again.
666
+ if let Some(existing) = session::find_live(paths, &signing_keys(paths)?) {
667
+ // What is shared is the *unlock*, not the session: the caller gets a
668
+ // session of its own under the same key — its own token, no grants.
669
+ // So a subagent still approves its own reads, and `/vault lock` in one
670
+ // tab locks that tab only, while nobody is asked for the password a
671
+ // second time.
672
+ let store = open_store(paths)?;
673
+ let Some(key) = existing.key() else { return Ok(existing) };
674
+ let mut own = Session::new(&existing.requester, existing.idle_ms, existing.expires_at, &store, &key);
675
+ own.kind = existing.kind;
676
+ let (host, wrap) = signing_keys(paths)?;
677
+ let signer = match existing.signed_by.as_deref() {
678
+ Some("host") => host.map(session::Signer::Host),
679
+ Some("wrap") => wrap.map(session::Signer::Wrap),
680
+ _ => None,
681
+ };
682
+ if let Some(signer) = signer {
683
+ own.save(paths, &signer)?;
684
+ return Ok(own);
685
+ }
686
+ return Ok(existing);
687
+ }
646
688
  // `vault.unlock = every`: no token exists by design. The password comes
647
689
  // with the call, opens the store in memory, and leaves with it. The hint
648
690
  // in the file header says to ask; the settings under the key decide.
@@ -1046,14 +1088,9 @@ fn settings(
1046
1088
  // The settings live inside the store's ciphertext: reading them needs the
1047
1089
  // store's key, i.e. an unlocked session. That is the whole point — there
1048
1090
  // is no file an agent could edit.
1049
- // In `every` mode the call brings its own password: it opens the store
1050
- // for this call and is remembered, so a change that must verify the
1051
- // master password does not ask for it a second time.
1052
- let mut every_password: Option<zeroize::Zeroizing<String>> = None;
1053
1091
  let session = load_session(paths, token)?;
1054
1092
  let store = open_store(paths)?;
1055
1093
  let mut config = payload_with(&session, &store)?.config;
1056
- EVERY_PASSWORD.with(|cell| every_password = cell.borrow().clone());
1057
1094
 
1058
1095
  let Some(raw_key) = key.filter(|k| !k.trim().is_empty()) else {
1059
1096
  let value = settings_value(&config, paths);
@@ -1094,7 +1131,7 @@ fn settings(
1094
1131
  let payload = payload_with(&session, &store)?;
1095
1132
  (payload, crypto::Key::new([0u8; 32]))
1096
1133
  } else {
1097
- verify_master_with(paths, &store, password_stdin, tr("switching the unlock policy", "切换解锁模式"), every_password.as_ref())?
1134
+ verify_master_with(paths, &store, password_stdin, tr("switching the unlock policy", "切换解锁模式"))?
1098
1135
  };
1099
1136
  config.unlock.mode = mode;
1100
1137
  if let Some(hours) = hours {
@@ -1209,22 +1246,22 @@ fn verify_master(
1209
1246
  password_stdin: bool,
1210
1247
  why: &str,
1211
1248
  ) -> Result<(crypto::Payload, crypto::Key), Fault> {
1212
- verify_master_with(paths, store, password_stdin, why, None)
1249
+ verify_master_with(paths, store, password_stdin, why)
1213
1250
  }
1214
1251
 
1215
- /// The same, able to reuse a password this call already proved (an `every`
1216
- /// session was opened with it moments ago): the user is not asked twice.
1252
+ /// Prove the master password. The sources, in order: the password an `every`
1253
+ /// call was opened with (already proven, never asked twice), `AI_VAULT_PASSWORD`
1254
+ /// from a host that asked in its own UI, `--password-stdin`, then a window.
1217
1255
  fn verify_master_with(
1218
1256
  paths: &Paths,
1219
1257
  store: &crypto::StoreFile,
1220
1258
  password_stdin: bool,
1221
1259
  why: &str,
1222
- proven: Option<&zeroize::Zeroizing<String>>,
1223
1260
  ) -> Result<(crypto::Payload, crypto::Key), Fault> {
1224
- let password = match proven {
1225
- Some(password) => password.clone(),
1226
- None if password_stdin => zeroize::Zeroizing::new(read_password()?),
1227
- None => zeroize::Zeroizing::new(ask_password(tr("ai-vault · master password", "ai-vault · 主密码"), why)?),
1261
+ let every = EVERY_PASSWORD.with(|cell| cell.borrow().clone());
1262
+ let password = match every {
1263
+ Some(password) => password,
1264
+ None => master_password_from(why, password_stdin)?,
1228
1265
  };
1229
1266
  crypto::open_with_passphrase(store, &password).map_err(|e| match e {
1230
1267
  crypto::OpenError::WrongPassword => {
@@ -1320,6 +1357,10 @@ fn status(paths: &Paths, out: &Out, token: Option<String>) -> Outcome {
1320
1357
  let value = json!({
1321
1358
  "ok": true,
1322
1359
  "unlocked": true,
1360
+ // The session this call ran under: when the caller came without a
1361
+ // token and adopted (or was given) one, this is how it learns the
1362
+ // token to sign its relayed approvals with.
1363
+ "token": if session.kind == session::SessionKind::Auto { None } else { Some(session.token.clone()) },
1323
1364
  "items": items.len(),
1324
1365
  "requester": session.requester,
1325
1366
  "idleMs": session.idle_ms,
@@ -91,7 +91,7 @@ impl ImportPolicy {
91
91
  }
92
92
  }
93
93
 
94
- #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
94
+ #[derive(Debug, Clone, Copy, Serialize)]
95
95
  pub struct UnlockPolicy {
96
96
  pub mode: UnlockMode,
97
97
  /// `Time` mode only: hours between password prompts.
@@ -110,6 +110,29 @@ fn default_confirm() -> bool {
110
110
  false
111
111
  }
112
112
 
113
+ /// The store's own policy reads its mode the way the settings command does:
114
+ /// `session` — the mode that was removed — is `time`, so a legacy file or an
115
+ /// older ciphertext cannot carry a per-process policy back to life.
116
+ impl<'de> Deserialize<'de> for UnlockPolicy {
117
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
118
+ #[derive(Deserialize)]
119
+ struct Raw {
120
+ #[serde(default)]
121
+ mode: Option<UnlockMode>,
122
+ #[serde(default = "default_hours")]
123
+ hours: i64,
124
+ #[serde(default = "default_confirm")]
125
+ confirm: bool,
126
+ }
127
+ let raw = Raw::deserialize(deserializer)?;
128
+ let mode = raw
129
+ .mode
130
+ .map(|m| if m == UnlockMode::Session { UnlockMode::Time } else { m })
131
+ .unwrap_or(UnlockMode::Time);
132
+ Ok(UnlockPolicy { mode, hours: raw.hours, confirm: raw.confirm })
133
+ }
134
+ }
135
+
113
136
  /// The store's own default: an afternoon's work without asking again.
114
137
  fn default_hours() -> i64 {
115
138
  4
@@ -127,14 +150,12 @@ impl Default for UnlockPolicy {
127
150
  }
128
151
 
129
152
  /// How a third-party CLI's credential is kept on disk.
130
- #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
153
+ #[derive(Debug, Clone, Copy, Serialize)]
131
154
  pub struct StorePolicy {
132
155
  /// `never` keeps the credential in the store directory (sealed), so the
133
156
  /// CLI needs no keychain or password; `time` does the same with a
134
157
  /// deadline; `session` (default) leaves it in the CLI's own keychain.
135
- #[serde(default = "default_bw_mode")]
136
158
  pub unlock: UnlockMode,
137
- #[serde(default = "default_key_hours")]
138
159
  pub hours: i64,
139
160
  }
140
161
 
@@ -144,6 +165,26 @@ impl Default for StorePolicy {
144
165
  }
145
166
  }
146
167
 
168
+ /// The Bitwarden and Ente keys have no `every`. A file that says otherwise is
169
+ /// not accepted as "keep it forever", which is what a plain `UnlockMode`
170
+ /// would have made of it: the whole entry falls back to the default.
171
+ impl<'de> Deserialize<'de> for StorePolicy {
172
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
173
+ #[derive(Deserialize)]
174
+ struct Raw {
175
+ #[serde(default = "default_bw_mode")]
176
+ unlock: UnlockMode,
177
+ #[serde(default = "default_key_hours")]
178
+ hours: i64,
179
+ }
180
+ let raw = Raw::deserialize(deserializer)?;
181
+ if raw.unlock == UnlockMode::Every {
182
+ return Err(serde::de::Error::custom("`every` is not a mode for the Bitwarden and Ente keys (never, time or session)"));
183
+ }
184
+ Ok(StorePolicy { unlock: raw.unlock, hours: raw.hours })
185
+ }
186
+ }
187
+
147
188
  #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
148
189
  pub struct BitwardenPolicy {
149
190
  #[serde(flatten)]
@@ -236,6 +277,14 @@ mod tests {
236
277
  assert_eq!(config.bitwarden.import, ImportPolicy::Ask);
237
278
  }
238
279
 
280
+ #[test]
281
+ fn the_keys_refuse_every() {
282
+ let err = serde_json::from_str::<Config>(r#"{"bitwarden":{"unlock":"every","hours":8}}"#);
283
+ assert!(err.is_err(), "every for a key must not be read as a mode");
284
+ let ok = serde_json::from_str::<Config>(r#"{"ente":{"unlock":"time","hours":2}}"#).unwrap();
285
+ assert_eq!(ok.ente.unlock, UnlockMode::Time);
286
+ }
287
+
239
288
  #[test]
240
289
  fn old_configs_still_load() {
241
290
  // A config written by the previous version had only `unlock`.
@@ -287,6 +287,38 @@ pub fn load(paths: &Paths, token: &str, host_secret: Option<&str>, wrap_key: Opt
287
287
  Ok(session)
288
288
  }
289
289
 
290
+ /// The newest live token of this store that the caller can verify — one
291
+ /// opened by any process, since they all sign under the store-wide host
292
+ /// secret (or, for a human at a terminal, the wrap key). `time` mode's
293
+ /// cross-process unlock rests on this: a call without a token adopts an
294
+ /// existing one rather than asking for the password again.
295
+ pub fn find_live(paths: &Paths, keys: &(Option<String>, Option<String>)) -> Option<Session> {
296
+ let current = crypto::read_store(&paths.store()).ok().flatten().map(|store| crypto::store_id(&store))?;
297
+ let now = now_ms();
298
+ let mut best: Option<Session> = None;
299
+ if let Ok(entries) = fs::read_dir(paths.sessions()) {
300
+ for entry in entries.flatten() {
301
+ let path = entry.path();
302
+ if path.extension().and_then(|e| e.to_str()) != Some("json") {
303
+ continue;
304
+ }
305
+ let Ok(text) = fs::read_to_string(&path) else { continue };
306
+ let Ok(session) = serde_json::from_str::<Session>(&text) else { continue };
307
+ if session.store_id != current || session.expired(now) || session.kind == SessionKind::Every {
308
+ continue;
309
+ }
310
+ if !session.verifies(keys.0.as_deref(), keys.1.as_deref()) {
311
+ continue;
312
+ }
313
+ let newer = best.as_ref().map_or(true, |b| session.last_active > b.last_active);
314
+ if newer {
315
+ best = Some(session);
316
+ }
317
+ }
318
+ }
319
+ best
320
+ }
321
+
290
322
  pub fn delete(paths: &Paths, token: &str) -> bool {
291
323
  fs::remove_file(paths.session_file(token)).is_ok()
292
324
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaolikt/ai-vault",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable, Linux/macOS/Windows) plus the pi-ai-vault extension for pi and omp.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,11 +33,11 @@
33
33
  "access": "public"
34
34
  },
35
35
  "optionalDependencies": {
36
- "@xiaolikt/ai-vault-linux-x64": "0.14.0",
37
- "@xiaolikt/ai-vault-linux-arm64": "0.14.0",
38
- "@xiaolikt/ai-vault-win32-x64": "0.14.0",
39
- "@xiaolikt/ai-vault-darwin-arm64": "0.14.0",
40
- "@xiaolikt/ai-vault-darwin-x64": "0.14.0"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.14.1",
37
+ "@xiaolikt/ai-vault-linux-arm64": "0.14.1",
38
+ "@xiaolikt/ai-vault-win32-x64": "0.14.1",
39
+ "@xiaolikt/ai-vault-darwin-arm64": "0.14.1",
40
+ "@xiaolikt/ai-vault-darwin-x64": "0.14.1"
41
41
  },
42
42
  "files": [
43
43
  "bin",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store, live Bitwarden and Ente Auth. Works in pi and in omp (the omp fork reads the same manifest).",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "security"
26
26
  ],
27
27
  "dependencies": {
28
- "@xiaolikt/ai-vault": "0.14.0"
28
+ "@xiaolikt/ai-vault": "0.14.1"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
@@ -57,7 +57,7 @@ import type { Draft } from "./types.js";
57
57
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
58
58
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
59
59
  import { npmShimLaunch, type CliLaunch } from "./cli.js";
60
- import { getSettingsSafe, settingsCli, settingsToken } from "./settings.js";
60
+ import { getSettingsSafe, settingsCli, settingsOpts, settingsToken } from "./settings.js";
61
61
  import { tr } from "./i18n.js";
62
62
  import { scrubDeep, scrubText } from "./scrub.js";
63
63
 
@@ -676,7 +676,7 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
676
676
  // directory), so Bitwarden costs no window at all.
677
677
  if (policy.unlock !== "session") {
678
678
  try {
679
- const saved = await settingsCli().json<{ key: string }>(["bw-session", "get"], { signal });
679
+ const saved = await settingsCli().json<{ key: string }>(["bw-session", "get"], { signal, ...settingsOpts() });
680
680
  if (saved?.key) {
681
681
  const verify = await bwStatus(saved.key, signal);
682
682
  if (verify?.status === "unlocked") {
@@ -720,7 +720,7 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
720
720
  // Keep the key where the CLI can hand it back; the file's expiry comes
721
721
  // from the bitwarden.hours policy.
722
722
  const token = settingsToken();
723
- await settingsCli().run(["bw-session", "put", ...(token ? ["--token", token] : [])], { stdin: key }).catch(() => undefined);
723
+ await settingsCli().run(["bw-session", "put", ...(token ? ["--token", token] : [])], { stdin: key, ...settingsOpts() }).catch(() => undefined);
724
724
  }
725
725
  await auditEvent("unlock", "ok", st.sessionLabel);
726
726
  // Refresh in the background: a full sync can take seconds on large vaults.
@@ -26,7 +26,7 @@ import { Type } from "typebox";
26
26
  import { auditEvent } from "./bitwarden.js";
27
27
  import { confirmWindow, forDialog } from "./prompt.js";
28
28
  import { withTier } from "./host.js";
29
- import { getSettingsSafe, settingsCli } from "./settings.js";
29
+ import { getSettingsSafe, settingsCli, settingsOpts } from "./settings.js";
30
30
 
31
31
  export interface EnteCodeMeta {
32
32
  id: string;
@@ -94,7 +94,7 @@ async function enteEnv(signal?: AbortSignal): Promise<Record<string, string | un
94
94
  const settings = await getSettingsSafe(signal);
95
95
  if (settings.ente.unlock === "session") return env;
96
96
  try {
97
- const sealed = await settingsCli().json<{ key: string }>(["ente-session", "get"], { signal });
97
+ const sealed = await settingsCli().json<{ key: string }>(["ente-session", "get"], { signal, ...settingsOpts() });
98
98
  if (sealed?.key) env.ENTE_CLI_VAULT_KEY = sealed.key;
99
99
  } catch {
100
100
  // No key saved yet, or it expired: ente will fall back to the keychain,
@@ -29,7 +29,7 @@ import type { Draft, ItemType } from "./types.js";
29
29
  import { registerEnte } from "./ente.js";
30
30
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
31
31
  import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
32
- import { forgetSettings, getSettingsSafe, setSettingsToken, settingsCli, settingsToken, type Settings } from "./settings.js";
32
+ import { forgetSettings, getSettingsSafe, setEveryPassword, setSettingsToken, settingsCli, settingsOpts, settingsToken, type Settings } from "./settings.js";
33
33
 
34
34
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
35
35
 
@@ -40,6 +40,8 @@ type UnlockModeName = "never" | "time" | "every";
40
40
  interface StatusResult {
41
41
  ok: boolean;
42
42
  unlocked: boolean;
43
+ /** The session the call ran under; a binding that came without a token adopts it. */
44
+ token?: string | null;
43
45
  items: number;
44
46
  requester: string;
45
47
  idleMs: number;
@@ -152,6 +154,7 @@ async function lockNow(scope: Scope): Promise<void> {
152
154
  scope.epoch++;
153
155
  scope.items = 0;
154
156
  setSettingsToken(undefined);
157
+ setEveryPassword(undefined);
155
158
  forgetSettings();
156
159
  if (!token || !cli.available) return;
157
160
  try {
@@ -215,7 +218,11 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
215
218
  scope.items = status.items;
216
219
  scope.mode = status.mode;
217
220
  scope.auto = status.auto;
218
- setSettingsToken(undefined);
221
+ // In `time` mode the CLI found an existing unlock and minted a
222
+ // session of our own under it: keep that token, so relayed
223
+ // approvals are signed for the session that will check them.
224
+ scope.token = status.token ?? undefined;
225
+ setSettingsToken(scope.token);
219
226
  return true;
220
227
  } catch (error) {
221
228
  if (error instanceof CliError && /not initialized/i.test(error.message)) {
@@ -231,6 +238,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
231
238
  scope.items = status.items;
232
239
  scope.mode = "every";
233
240
  scope.everyPassword = password;
241
+ setEveryPassword(password);
234
242
  return true;
235
243
  } catch (retryError) {
236
244
  if (retryError instanceof CliError && retryError.auth) {
@@ -284,7 +292,10 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
284
292
  // next call asks again.
285
293
  scope.token = result.mode === "never" || result.mode === "every" ? undefined : result.token;
286
294
  scope.items = result.items;
287
- if (result.mode === "every") scope.everyPassword = lastUnlockPassword;
295
+ if (result.mode === "every") {
296
+ scope.everyPassword = lastUnlockPassword;
297
+ setEveryPassword(lastUnlockPassword);
298
+ }
288
299
  setSettingsToken(scope.token);
289
300
  return true;
290
301
  } catch (error) {
@@ -332,6 +343,7 @@ function vaultListTool(scope: Scope): ToolDefinition<typeof vaultListParams, { o
332
343
  return failure(scope, error);
333
344
  } finally {
334
345
  scope.everyPassword = undefined;
346
+ setEveryPassword(undefined);
335
347
  }
336
348
  },
337
349
  };
@@ -489,6 +501,7 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
489
501
  return failure(scope, error);
490
502
  } finally {
491
503
  scope.everyPassword = undefined;
504
+ setEveryPassword(undefined);
492
505
  }
493
506
  },
494
507
  };
@@ -615,7 +628,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
615
628
  if (!name) return "cancelled: no entry name";
616
629
 
617
630
  const kind = req.type ?? "login";
618
- const args = ["add", "--name", name, "--type", kind, "--token", scope.token!];
631
+ const args = ["add", "--name", name, "--type", kind, ...tokenArgs(scope)];
619
632
  if (req.username !== undefined) args.push("--username", req.username);
620
633
  if (req.uri?.trim()) args.push("--uri", req.uri.trim());
621
634
  if (req.notes?.trim()) args.push("--notes", req.notes.trim());
@@ -723,9 +736,9 @@ async function importBitwarden(
723
736
  return { text: "nothing matched; nothing imported", ok: false, count: 0 };
724
737
  }
725
738
  try {
726
- const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
739
+ const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
727
740
  stdin: JSON.stringify(drafts),
728
- signal,
741
+ ...callOpts(scope, signal),
729
742
  });
730
743
  scope.items += saved.count;
731
744
  setStatus(ctx, scope);
@@ -901,14 +914,15 @@ function commandHandler(scope: Scope, bw: BwState) {
901
914
  case "ente-key": {
902
915
  // Ente's unattended key: generated by `ente vault key generate`.
903
916
  // Saved sealed, so `ente.unlock = never | time` can use it.
917
+ if (!(await ensureUnlocked(scope, ctx))) return;
904
918
  const key = await promptSecret(dialogs(ctx), tr("ai-vault · Ente key", "ai-vault · Ente 密钥"), tr("the key printed by ente vault key generate", "ente vault key generate 输出的密钥"));
905
919
  if (!key) {
906
920
  note(ctx, tr("cancelled", "已取消"), "warning");
907
921
  return;
908
922
  }
909
923
  try {
910
- const args = ["ente-session", "put"];
911
- await cli.run(args, { stdin: key });
924
+ const args = ["ente-session", "put", ...tokenArgs(scope)];
925
+ await cli.run(args, { stdin: key, ...callOpts(scope) });
912
926
  forgetSettings();
913
927
  note(ctx, tr("saved (sealed). You can now set /vault settings ente.unlock never", "已保存(封存)。现在可以设置 /vault settings ente.unlock never"));
914
928
  } catch (error) {
@@ -920,6 +934,7 @@ function commandHandler(scope: Scope, bw: BwState) {
920
934
  // /vault confirm show
921
935
  // /vault confirm off|on turn the per-read window off (asks the master password) / on
922
936
  const [arg] = rest;
937
+ if (!(await ensureUnlocked(scope, ctx))) return;
923
938
  if (!arg) {
924
939
  try {
925
940
  const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)], callOpts(scope));
@@ -959,6 +974,9 @@ function commandHandler(scope: Scope, bw: BwState) {
959
974
  case "settings": {
960
975
  const [key, ...valueParts] = rest;
961
976
  const value = valueParts.join(" ").trim();
977
+ // Reading the settings means opening the store: in `every` mode
978
+ // that is a password for this call, asked here.
979
+ if (!(await ensureUnlocked(scope, ctx))) return;
962
980
  try {
963
981
  if (!key) {
964
982
  note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)], callOpts(scope))));
@@ -986,6 +1004,7 @@ function commandHandler(scope: Scope, bw: BwState) {
986
1004
  }
987
1005
  case "mode": {
988
1006
  const [sub, hoursArg] = rest;
1007
+ if (!(await ensureUnlocked(scope, ctx))) return;
989
1008
  if (!sub || sub === "get" || sub === "status") {
990
1009
  try {
991
1010
  const current = await cli.json<{ mode: string; hours: number; auto: boolean }>(["mode"]);
@@ -1004,8 +1023,8 @@ function commandHandler(scope: Scope, bw: BwState) {
1004
1023
  }
1005
1024
  return;
1006
1025
  }
1007
- if (!["never", "time", "session", "no-password"].includes(sub)) {
1008
- note(ctx, tr("usage: /vault mode [never|time|session] [hours]", "用法: /vault mode [never|time|session] [小时]"), "warning");
1026
+ if (!["every", "time", "never", "no-password", "every-time"].includes(sub)) {
1027
+ note(ctx, tr("usage: /vault mode [every|time|never] [hours]", "用法: /vault mode [every|time|never] [小时]"), "warning");
1009
1028
  return;
1010
1029
  }
1011
1030
  const args = ["mode", "set", sub];
@@ -1021,9 +1040,9 @@ function commandHandler(scope: Scope, bw: BwState) {
1021
1040
  const how =
1022
1041
  result.mode === "never"
1023
1042
  ? tr("no password from now on (the key is on disk: anything that can read your files can read every password in the store)", "以后免密(密钥已写盘,任何能读你文件的程序都能读到库里的密码)")
1024
- : result.mode === "time"
1025
- ? tr(`the password is asked again every ${result.hours} hours from now on`, `以后每 ${result.hours} 小时要一次密码`)
1026
- : tr("the password is asked once per session from now on", "以后每个会话要一次密码");
1043
+ : result.mode === "every"
1044
+ ? tr("the password is asked on every call from now on; nothing that can open the store is kept", "以后每次调用都要密码;不留任何能打开库的东西")
1045
+ : tr(`the password is asked again every ${result.hours} hours from now on`, `以后每 ${result.hours} 小时要一次密码`);
1027
1046
  note(ctx, `mode → ${result.mode},${how}`);
1028
1047
  } catch (error) {
1029
1048
  note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
@@ -1033,7 +1052,7 @@ function commandHandler(scope: Scope, bw: BwState) {
1033
1052
  case "list": {
1034
1053
  if (!(await ensureUnlocked(scope, ctx))) return;
1035
1054
  try {
1036
- const result = await cli.json<ListResult>(["list", "--token", scope.token!]);
1055
+ const result = await cli.json<ListResult>(["list", ...tokenArgs(scope)], callOpts(scope));
1037
1056
  scope.items = result.count;
1038
1057
  const rows = result.items.map((i) => `${i.name}\t${i.username ?? ""}\t${i.uris[0] ?? ""}`);
1039
1058
  note(ctx, rows.join("\n") || "(empty)");
@@ -1077,9 +1096,9 @@ function commandHandler(scope: Scope, bw: BwState) {
1077
1096
  note(ctx, tr("usage: /vault remove <name>", "用法: /vault remove <名称>"), "warning");
1078
1097
  return;
1079
1098
  }
1080
- const args = ["remove", name, "--token", scope.token!];
1099
+ const args = ["remove", name, ...tokenArgs(scope)];
1081
1100
  try {
1082
- const result = await cli.json<RemovingResult>(args);
1101
+ const result = await cli.json<RemovingResult>(args, callOpts(scope));
1083
1102
  if (result.removed) scope.items = Math.max(0, scope.items - 1);
1084
1103
  setStatus(ctx, scope);
1085
1104
  note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
@@ -1091,7 +1110,7 @@ function commandHandler(scope: Scope, bw: BwState) {
1091
1110
  const sure = await confirmWindow(dialogs(ctx), tr("ai-vault · delete entry", "ai-vault · 删除条目"), tr(`Delete "${forDialog(name)}"? This cannot be undone.`, `删除「${forDialog(name)}」?删除后无法恢复。`));
1092
1111
  if (!sure) return;
1093
1112
  try {
1094
- const result = await cli.json<RemovingResult>([...args, "--yes"]);
1113
+ const result = await cli.json<RemovingResult>([...args, "--yes"], callOpts(scope));
1095
1114
  if (result.removed) scope.items = Math.max(0, scope.items - 1);
1096
1115
  setStatus(ctx, scope);
1097
1116
  note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
@@ -1111,7 +1130,7 @@ function commandHandler(scope: Scope, bw: BwState) {
1111
1130
  note(ctx, tr("unlock first; usage: /vault grant <name> [minutes] (quote names with spaces)", "先解锁;用法: /vault grant <名称> [分钟](带空格的名称加引号)"), "warning");
1112
1131
  return;
1113
1132
  }
1114
- const args = ["grant", name, "--token", scope.token!];
1133
+ const args = ["grant", name, ...tokenArgs(scope)];
1115
1134
  if (minutes) args.push("--minutes", minutes);
1116
1135
  try {
1117
1136
  // A standing grant costs the master password, like a mode change.
@@ -1129,7 +1148,7 @@ function commandHandler(scope: Scope, bw: BwState) {
1129
1148
  case "revoke": {
1130
1149
  if (!(await ensureUnlocked(scope, ctx))) return;
1131
1150
  const target = rest[0] === "all" ? "all" : rest.join(" ").trim();
1132
- const args = ["revoke", "--token", scope.token!];
1151
+ const args = ["revoke", ...tokenArgs(scope)];
1133
1152
  if (target === "all") args.push("--all");
1134
1153
  else if (target) args.push(target);
1135
1154
  else {
@@ -1166,9 +1185,9 @@ function commandHandler(scope: Scope, bw: BwState) {
1166
1185
  return;
1167
1186
  }
1168
1187
  if (!(await ensureUnlocked(scope, ctx))) return;
1169
- const args = ["import", path, "--token", scope.token!];
1188
+ const args = ["import", path, ...tokenArgs(scope)];
1170
1189
  try {
1171
- const result = await cli.json<SaveResult>(args);
1190
+ const result = await cli.json<SaveResult>(args, callOpts(scope));
1172
1191
  scope.items += result.count;
1173
1192
  setStatus(ctx, scope);
1174
1193
  note(ctx, `imported ${result.count} login items`);
@@ -1184,7 +1203,7 @@ function commandHandler(scope: Scope, bw: BwState) {
1184
1203
  );
1185
1204
  if (!sure) return;
1186
1205
  try {
1187
- const result = await cli.json<SaveResult>([...args, "--yes"]);
1206
+ const result = await cli.json<SaveResult>([...args, "--yes"], callOpts(scope));
1188
1207
  scope.items += result.count;
1189
1208
  setStatus(ctx, scope);
1190
1209
  note(ctx, `imported ${result.count} login items`);
@@ -50,6 +50,8 @@ let cache: { at: number; value: Settings } | undefined;
50
50
  * the binding that unlocked sets this before asking.
51
51
  */
52
52
  let sessionToken: string | undefined;
53
+ /** In `every` mode there is no token: the settings are read with the call's password. */
54
+ let everyPassword: string | undefined;
53
55
 
54
56
  export function setSettingsToken(token: string | undefined): void {
55
57
  if (token !== sessionToken) {
@@ -58,17 +60,27 @@ export function setSettingsToken(token: string | undefined): void {
58
60
  }
59
61
  }
60
62
 
63
+ /** The password an `every` call was opened with, for reading the settings under it. */
64
+ export function setEveryPassword(password: string | undefined): void {
65
+ everyPassword = password;
66
+ }
67
+
61
68
  export function settingsToken(): string | undefined {
62
69
  return sessionToken;
63
70
  }
64
71
 
72
+ /** CLI options for a settings read under whatever this binding holds. */
73
+ export function settingsOpts(): { password?: string } {
74
+ return everyPassword !== undefined ? { password: everyPassword } : {};
75
+ }
76
+
65
77
  /**
66
78
  * Settings change rarely, so a short cache keeps a Bitwarden call from paying
67
79
  * for the read. `/vault settings ...` drops it explicitly.
68
80
  */
69
81
  export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
70
82
  if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
71
- const value = await settingsCli().json<Settings>(["settings", ...(sessionToken ? ["--token", sessionToken] : [])], { signal });
83
+ const value = await settingsCli().json<Settings>(["settings", ...(sessionToken ? ["--token", sessionToken] : [])], { signal, ...settingsOpts() });
72
84
  cache = { at: Date.now(), value };
73
85
  return value;
74
86
  }
package/test/cli.sh CHANGED
@@ -253,8 +253,11 @@ grep -q '"confirm"' "$AI_VAULT_DIR/store.json" && bad "settings are readable in
253
253
  # protection, so the attack gains nothing.
254
254
  echo '{"vault":{"unlock":"session","hours":8,"confirm":false}}' >"$AI_VAULT_DIR/config.json"
255
255
  TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
256
+ [[ -n "$TKH" ]] && ok "the unlock after a legacy file still mints a token (mode read as time, not session)" || bad "no token: the legacy session mode came through as per-process"
256
257
  setting vault.confirm --token "$TKH" >"$TMP/c2"
257
258
  [[ "$(setting_value "$TMP/c2")" == "true" ]] && ok "the legacy file's confirm=false did not make it in" || bad "confirm=false was migrated from the file"
259
+ setting vault.unlock --token "$TKH" >"$TMP/c2s"
260
+ [[ "$(setting_value "$TMP/c2s")" == "time" ]] && ok "the legacy file's session is read as time" || bad "session was carried into the store"
258
261
  [[ -f "$AI_VAULT_DIR/config.json" ]] && bad "config.json still there" || ok "the legacy file was removed after migration"
259
262
  echo '{"vault":{"unlock":"never","hours":8,"confirm":true}}' >"$AI_VAULT_DIR/config.json"
260
263
  TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | python3 -c 'import json,sys;d=json.load(sys.stdin);print(d["token"] if not d.get("auto") else "")')
@@ -314,10 +317,25 @@ printf 'wrong\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings
314
317
  printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock time --password-stdin --json >"$TMP/e4"
315
318
  [[ "$(grep -o '"unlock":"time"' "$TMP/e4" | head -1)" ]] && ok "leaving every with the right password, asked once" || bad "could not leave every"
316
319
  printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | python3 -c 'import json,sys;d=json.load(sys.stdin);print(" back to time: token minted:", bool(d.get("token")))'
317
- # tamper: the plaintext hint only says "ask"; clearing it must not open anything
318
- printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock every --password-stdin --json >/dev/null
320
+ # tamper: the plaintext hint only says "ask"; clearing it must not open anything.
321
+ # Enter `every` for real, and prove it took before tampering.
322
+ TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
323
+ setting vault.unlock every --token "$TKH" >"$TMP/ev"
324
+ grep -q '"unlock": *"every"' "$TMP/ev" && ok "entered every" || bad "could not enter every for the hint test"
325
+ grep -q '"askEvery": *true' "$AI_VAULT_DIR/store.json" && ok "the hint is set" || bad "hint missing in every mode"
326
+ # and back, through the real path (every -> time needs the password once) —
327
+ # BEFORE tampering, since a cleared hint leaves the CLI unable to ask.
328
+ printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock time --password-stdin --json >"$TMP/back" 2>"$TMP/backerr"
329
+ grep -q '"unlock": *"time"' "$TMP/back" && ok "left every with one password" || bad "could not leave every: $(head -c 160 "$TMP/backerr")"
330
+ # Now the tamper, on a throwaway copy of the store: enter every, clear the hint.
331
+ TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
332
+ setting vault.unlock every --token "$TKH" >/dev/null
333
+ cp "$AI_VAULT_DIR/store.json" "$TMP/store.bak2"
319
334
  python3 -c "import json;p='$AI_VAULT_DIR/store.json';d=json.load(open(p));d.pop('askEvery',None);json.dump(d,open(p,'w'))"
320
335
  check "hint cleared: the CLI stops asking and finds no token (nothing lowered)" 5 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' list --password-stdin"
336
+ check "hint cleared: a bare call is locked too" 5 bash -c "env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' list --json"
337
+ cp "$TMP/store.bak2" "$AI_VAULT_DIR/store.json"
338
+ printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock time --password-stdin --json >/dev/null
321
339
  export AI_VAULT_DIR="$MAIN_DIR" XDG_RUNTIME_DIR="$MAIN_RT"
322
340
 
323
341
  echo "== rekey (L2) =="
@@ -353,7 +371,10 @@ d = json.load(open(sys.argv[1]))
353
371
  assert d["mode"] == "never" and d["auto"] is True, d
354
372
  PY
355
373
  check "back to session mode" 0 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' mode set session --password-stdin --token '$TOKEN_HUMAN' --json"
356
- check "session mode needs a token again" 5 "$BIN" status
374
+ # No `session` mode any more. Back in `time`, a bare call adopts the unlock
375
+ # that is still on disk (that is what `time` means) — not a lock, not a prompt.
376
+ TKH2=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
377
+ check "back in time: a bare call adopts the existing unlock" 0 bash -c "env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' status --json"
357
378
 
358
379
  echo "== settings =="
359
380
  check "settings prints everything" 0 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' settings --password-stdin --token '$TOKEN_HUMAN' --json"
@@ -105,7 +105,7 @@ test("a subagent has its own session: the parent's grant is not inherited", asyn
105
105
  assert.equal(prompts("--question"), before + 1, "the subagent needs its own approval");
106
106
  });
107
107
 
108
- test("/new drops only the binding that switched", async () => {
108
+ test("/new drops the binding's own session and grants, not the machine-wide unlock", async () => {
109
109
  const a = bind(aiVault, true);
110
110
  const b = bind(aiVault, true);
111
111
  const ac = makeCtx({ sessionId: "11111111-0000-4000-8000-000000000001" }).ctx;
@@ -119,12 +119,14 @@ test("/new drops only the binding that switched", async () => {
119
119
 
120
120
  answers.master(dir, PW);
121
121
  const before = masterPrompts();
122
+ // `time` mode: the unlock is the machine's, so the switched binding picks
123
+ // it back up without a password — only its own session and grants are gone.
122
124
  assert.equal((await a.tool("vault_list", {}, ac)).isError, undefined);
123
- assert.equal(masterPrompts(), before + 1, "the switched binding unlocks again");
125
+ assert.equal(masterPrompts(), before, "/new does not ask for the password again");
124
126
 
125
127
  const untouched = await b.tool("vault_list", {}, bc);
126
128
  assert.equal(untouched.isError, undefined);
127
- assert.equal(masterPrompts(), before + 1, "the other binding keeps its token");
129
+ assert.equal(masterPrompts(), before, "the other binding keeps its token");
128
130
  });
129
131
 
130
132
  test("a missing entry names what is available", async () => {
@@ -484,3 +486,39 @@ test("every mode: each call asks for the master password, nothing that opens the
484
486
  }
485
487
  }
486
488
  });
489
+
490
+ test("time mode: a second process with the store's secret adopts an existing unlock; one without it does not", async () => {
491
+ // The whole point of `time`: tab A unlocks, tab B (a fresh process, no
492
+ // token) reads without asking. droid's review found this was never true —
493
+ // the shared secret only let a token be *verified*, never *found*.
494
+ const { mkdtempSync, readdirSync } = await import("node:fs");
495
+ const { join } = await import("node:path");
496
+ const { spawnSync } = await import("node:child_process");
497
+ const box = mkdtempSync(join(process.env.TMPDIR ?? "/tmp", "ai-vault-time-"));
498
+ const store = join(box, "store");
499
+ const runtime = join(box, "runtime");
500
+ const bin = process.env.AI_VAULT_BIN;
501
+ const secret = "a".repeat(64);
502
+ const asHost = (secret) => ({ ...process.env, AI_VAULT_DIR: store, XDG_RUNTIME_DIR: runtime, AI_VAULT_HOST: "1", AI_VAULT_HOST_SECRET: secret });
503
+ const run = (env, args, input) => spawnSync(bin, args, { input, env, encoding: "utf8" });
504
+ const { forgetSettings } = await import("../packages/pi-ai-vault/src/settings.ts");
505
+ forgetSettings();
506
+ try {
507
+ assert.equal(run(asHost(secret), ["init", "--password-stdin", "--json"], `${PW}\n`).status, 0);
508
+ const token = JSON.parse(run(asHost(secret), ["unlock", "--password-stdin", "--json"], `${PW}\n`).stdout).token;
509
+ assert.equal(run(asHost(secret), ["add", "--name", "Shared", "--username", "u", "--password-stdin", "--yes", "--token", token], "shared-pw\n").status, 0);
510
+ assert.ok(readdirSync(join(runtime, "ai-vault", "sessions")).length >= 1, "an unlock is on disk");
511
+ // Tab B: the same store secret, no token, a fresh process.
512
+ const adopted = run(asHost(secret), ["get", "Shared", "--json"]);
513
+ assert.equal(adopted.status, 0, adopted.stderr);
514
+ assert.equal(JSON.parse(adopted.stdout).password, "shared-pw");
515
+ // A process without the secret is refused, token or not.
516
+ assert.equal(run(asHost("0".repeat(64)), ["list", "--json"]).status, 5);
517
+ assert.equal(run(asHost("0".repeat(64)), ["status", "--token", token, "--json"]).status, 5);
518
+ // A human (the wrap key) cannot adopt a host's session either.
519
+ const human = { ...process.env, AI_VAULT_DIR: store, XDG_RUNTIME_DIR: runtime, AI_VAULT_HOST: "", AI_VAULT_HOST_SECRET: "" };
520
+ assert.equal(run(human, ["list", "--json"]).status, 5);
521
+ } finally {
522
+ forgetSettings();
523
+ }
524
+ });