@xiaolikt/ai-vault 0.11.0 → 0.12.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.
@@ -23,13 +23,13 @@ import {
23
23
  type BitwardenMeta,
24
24
  type BwState,
25
25
  } from "./bitwarden.js";
26
- import { CliError, VaultCli } from "./cli.js";
26
+ import { CliError } from "./cli.js";
27
27
  import { ITEM_TYPES, isSecretField, parseItemType } from "./import-map.js";
28
28
  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, type Settings } from "./settings.js";
32
+ import { forgetSettings, getSettingsSafe, setSettingsToken, settingsCli, settingsToken, type Settings } from "./settings.js";
33
33
 
34
34
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
35
35
 
@@ -100,7 +100,7 @@ interface Scope {
100
100
  unlocking?: Promise<boolean>;
101
101
  }
102
102
 
103
- const cli = new VaultCli();
103
+ const cli = settingsCli();
104
104
 
105
105
  const CLI_MISSING =
106
106
  tr("ai-vault CLI not found. Install it once for a machine-wide store: cargo install --path <repo>/crates/ai-vault (or point AI_VAULT_BIN at a compiled binary)", "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)");
@@ -148,6 +148,8 @@ async function lockNow(scope: Scope): Promise<void> {
148
148
  scope.token = undefined;
149
149
  scope.epoch++;
150
150
  scope.items = 0;
151
+ setSettingsToken(undefined);
152
+ forgetSettings();
151
153
  if (!token || !cli.available) return;
152
154
  try {
153
155
  await cli.run(["lock", "--token", token]);
@@ -174,6 +176,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
174
176
  scope.items = status.items;
175
177
  scope.mode = status.mode;
176
178
  scope.auto = false;
179
+ setSettingsToken(scope.token);
177
180
  return true;
178
181
  } catch (error) {
179
182
  if (!(error instanceof CliError) || !error.auth) {
@@ -194,6 +197,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
194
197
  scope.items = status.items;
195
198
  scope.mode = status.mode;
196
199
  scope.auto = status.auto;
200
+ setSettingsToken(undefined);
197
201
  return true;
198
202
  } catch (error) {
199
203
  if (error instanceof CliError && /not initialized/i.test(error.message)) {
@@ -237,6 +241,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
237
241
  // per-binding token would bring back a confirm window on every read.
238
242
  scope.token = result.mode === "never" ? undefined : result.token;
239
243
  scope.items = result.items;
244
+ setSettingsToken(scope.token);
240
245
  return true;
241
246
  } catch (error) {
242
247
  if (error instanceof CliError && error.auth) {
@@ -693,6 +698,7 @@ const HELP = [
693
698
  tr("/vault init create the machine-wide encrypted store (a dialog sets the master password)", "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)"),
694
699
  tr("/vault unlock | lock unlock / lock (clears this session's grants)", "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)"),
695
700
  tr("/vault mode [never|time|session] show/switch the unlock policy (switching needs the master password)", "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)"),
701
+ tr("/vault confirm [off|on] a window per read while unlocked (off asks the master password)", "/vault confirm [off|on] 解锁后每次读取是否弹确认窗(关要主密码)"),
696
702
  tr("/vault settings [key value] show/change settings (vault.unlock, bitwarden.*, ente.* …)", "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)"),
697
703
  tr("/vault ente-key save Ente's ENTE_CLI_VAULT_KEY (no keychain, no login)", "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)"),
698
704
  tr("/vault status state and grants left", "/vault status 状态与授权剩余时间"),
@@ -861,22 +867,61 @@ function commandHandler(scope: Scope, bw: BwState) {
861
867
  }
862
868
  return;
863
869
  }
870
+ case "confirm": {
871
+ // /vault confirm show
872
+ // /vault confirm off|on turn the per-read window off (asks the master password) / on
873
+ const [arg] = rest;
874
+ if (!arg) {
875
+ try {
876
+ const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)]);
877
+ note(ctx, `vault.confirm: ${current.vault.confirm}${current.vault.confirm ? tr(" (a window per read while unlocked)", " (解锁后每次读取弹确认窗)") : tr(" (the unlock is the approval; reads are audited)", " (解锁即授权;读取仍记审计)")}`);
878
+ } catch (error) {
879
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
880
+ }
881
+ return;
882
+ }
883
+ const value = arg.toLowerCase();
884
+ if (!["off", "on", "false", "true"].includes(value)) {
885
+ note(ctx, tr("usage: /vault confirm [off|on]", "用法: /vault confirm [off|on]"), "warning");
886
+ return;
887
+ }
888
+ const turnOff = value === "off" || value === "false";
889
+ try {
890
+ const run = await cli.withPassword(["settings", "vault.confirm", turnOff ? "false" : "true", ...tokenArgs(scope)], () =>
891
+ promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("turn off the per-read confirmation", "关闭每次读取的确认窗")),
892
+ );
893
+ forgetSettings();
894
+ const updated = JSON.parse(run.stdout) as Settings;
895
+ note(
896
+ ctx,
897
+ updated.vault.confirm
898
+ ? tr("vault.confirm is on: every read opens a confirm window.", "vault.confirm 已开:每次读取弹确认窗。")
899
+ : tr(
900
+ "vault.confirm is off: while a session is unlocked, reads return without a window. Each read is still written to the audit log. Turning it back on: /vault confirm on",
901
+ "vault.confirm 已关:会话解锁期间读取不再弹窗。每次读取仍写审计。重新打开:/vault confirm on",
902
+ ),
903
+ );
904
+ } catch (error) {
905
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
906
+ }
907
+ return;
908
+ }
864
909
  case "settings": {
865
910
  const [key, ...valueParts] = rest;
866
911
  const value = valueParts.join(" ").trim();
867
912
  try {
868
913
  if (!key) {
869
- note(ctx, settingsText(await cli.json<Settings>(["settings"])));
914
+ note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)])));
870
915
  return;
871
916
  }
872
917
  if (!value) {
873
- const one = await cli.json<{ key: string; value: string }>(["settings", key]);
918
+ const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)]);
874
919
  note(ctx, `${one.key}: ${one.value}`);
875
920
  return;
876
921
  }
877
922
  // `vault.unlock` opens its own password window (or answers
878
923
  // needs-ui); the other keys do not prompt at all.
879
- const run = await cli.withPassword(["settings", key, value], () =>
924
+ const run = await cli.withPassword(["settings", key, value, ...tokenArgs(scope)], () =>
880
925
  promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
881
926
  );
882
927
  forgetSettings();
@@ -11,7 +11,7 @@ export type UnlockModeName = "never" | "time" | "session";
11
11
  export type ImportPolicy = "ask" | "always" | "never";
12
12
 
13
13
  export interface Settings {
14
- vault: { unlock: UnlockModeName; hours: number; auto: boolean };
14
+ vault: { unlock: UnlockModeName; hours: number; confirm: boolean; auto: boolean };
15
15
  bitwarden: {
16
16
  unlock: UnlockModeName;
17
17
  hours: number;
@@ -24,17 +24,42 @@ export interface Settings {
24
24
  }
25
25
 
26
26
  export const DEFAULT_SETTINGS: Settings = {
27
- vault: { unlock: "session", hours: 8, auto: false },
27
+ vault: { unlock: "session", hours: 8, confirm: true, auto: false },
28
28
  bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
29
29
  ente: { unlock: "session", hours: 8, persisted: false, expiresAt: null },
30
30
  };
31
31
 
32
- const cli = new VaultCli();
33
- let cache: { at: number; value: Settings } | undefined;
32
+ /**
33
+ * One CLI client for the whole extension. It carries the one `HostSecret`
34
+ * every call must be signed under: a second instance would have its own
35
+ * (empty) secret, and a call made through it would fail the session file's
36
+ * HMAC and get it deleted — locking the binding out. Keep this the same
37
+ * object the tools use.
38
+ */
39
+ let cli: VaultCli | undefined;
34
40
 
35
- /** The shared CLI client, for the pieces that read and write the settings. */
36
41
  export function settingsCli(): VaultCli {
37
- return cli;
42
+ return (cli ??= new VaultCli());
43
+ }
44
+
45
+ let cache: { at: number; value: Settings } | undefined;
46
+
47
+ /**
48
+ * The session token the settings are read under. The settings live inside the
49
+ * store's ciphertext, so reading them is a privileged call like any other;
50
+ * the binding that unlocked sets this before asking.
51
+ */
52
+ let sessionToken: string | undefined;
53
+
54
+ export function setSettingsToken(token: string | undefined): void {
55
+ if (token !== sessionToken) {
56
+ sessionToken = token;
57
+ cache = undefined;
58
+ }
59
+ }
60
+
61
+ export function settingsToken(): string | undefined {
62
+ return sessionToken;
38
63
  }
39
64
 
40
65
  /**
@@ -43,7 +68,7 @@ export function settingsCli(): VaultCli {
43
68
  */
44
69
  export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
45
70
  if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
46
- const value = await cli.json<Settings>(["settings"], { signal });
71
+ const value = await settingsCli().json<Settings>(["settings", ...(sessionToken ? ["--token", sessionToken] : [])], { signal });
47
72
  cache = { at: Date.now(), value };
48
73
  return value;
49
74
  }
@@ -60,3 +85,8 @@ export async function getSettingsSafe(signal?: AbortSignal): Promise<Settings> {
60
85
  export function forgetSettings(): void {
61
86
  cache = undefined;
62
87
  }
88
+
89
+ /** Tests change the store's settings from outside the process; let them drop the cache. */
90
+ process.on("ai-vault:settings-changed", () => {
91
+ cache = undefined;
92
+ });
package/test/cli.sh CHANGED
@@ -65,6 +65,20 @@ HOST_JSON=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json)
65
65
  ECHOED=$(printf '%s' "$HOST_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin).get('hostSecret',''))")
66
66
  [[ "$ECHOED" == "$HS" ]] && ok "the host's own secret is echoed back" || bad "hostSecret echo mismatch"
67
67
  TOKEN=$(printf '%s' "$HOST_JSON" | json token)
68
+ # The settings live inside the store: reading or changing them needs an
69
+ # unlocked session, and the changes that lower protection need the master
70
+ # password on stdin as well. `setting KEY [VALUE]` does both.
71
+ TOKEN_HUMAN=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
72
+ setting() {
73
+ local key="$1"; shift
74
+ local tok="$TOKEN_HUMAN" args=()
75
+ while [[ $# -gt 0 ]]; do
76
+ if [[ "$1" == "--token" ]]; then tok="$2"; shift 2; else args+=("$1"); shift; fi
77
+ done
78
+ printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings "$key" "${args[@]}" --password-stdin --token "$tok" --json
79
+ }
80
+ # The value of one setting, as `settings KEY` prints it.
81
+ setting_value() { python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['value'])" "$1"; }
68
82
  # relay <entry> <y|n>: a signed approval for the host's token.
69
83
  relay() {
70
84
  local ap
@@ -146,8 +160,8 @@ check "an edited token file is rejected" 5 bash -c "'$BIN' get Draft --token '$T
146
160
  check "M1: a junk file in the sessions dir is swept on the next call" 0 "$BIN" path --json
147
161
 
148
162
  echo "== sealed Bitwarden session (M4) =="
149
- check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
150
- check "store a bw session key" 0 bash -c "printf 'BW_BEARER_TOKEN_PLAINTEXT' | '$BIN' bw-session put --json"
163
+ check "switch bitwarden.unlock to never" 0 setting bitwarden.unlock never
164
+ check "store a bw session key" 0 bash -c "printf 'BW_BEARER_TOKEN_PLAINTEXT' | '$BIN' bw-session put --token '$TOKEN_HUMAN' --json"
151
165
  grep -q 'BW_BEARER_TOKEN_PLAINTEXT' "$AI_VAULT_DIR/bitwarden.session.json" && bad "the bw key is plaintext on disk" || ok "the bw key is not plaintext on disk"
152
166
  [[ -f "$AI_VAULT_DIR/.wrap" ]] && ok "a wrap key exists" || bad "no wrap key"
153
167
  [[ "$(mode_of "$AI_VAULT_DIR/.wrap")" == "600" ]] && ok "the wrap key is 0600" || bad "the wrap key is not 0600"
@@ -155,17 +169,17 @@ grep -q 'BW_BEARER_TOKEN_PLAINTEXT' "$AI_VAULT_DIR/bitwarden.session.json" && ba
155
169
  mv "$AI_VAULT_DIR/.wrap" "$TMP/wrap.bak"
156
170
  check "without the wrap key the session does not open" 1 "$BIN" bw-session get
157
171
  mv "$TMP/wrap.bak" "$AI_VAULT_DIR/.wrap"
158
- "$BIN" settings bitwarden.unlock session --json >/dev/null
172
+ setting bitwarden.unlock session >/dev/null
159
173
 
160
174
  echo "== ente sealed key (M4 pattern) =="
161
- check "ente.unlock is readable" 0 "$BIN" settings ente.unlock --json
162
- check "ente-session put refused in session mode" 1 bash -c "printf 'K' | '$BIN' ente-session put"
163
- check "switch ente.unlock to never" 0 "$BIN" settings ente.unlock never --json
164
- check "store the Ente vault key" 0 bash -c "printf 'ENTE_KEY_PLAINTEXT' | '$BIN' ente-session put --json"
175
+ check "ente.unlock is readable" 0 setting ente.unlock
176
+ check "ente-session put refused in session mode" 1 bash -c "printf 'K' | '$BIN' ente-session put --token '$TOKEN_HUMAN'"
177
+ check "switch ente.unlock to never" 0 setting ente.unlock never
178
+ check "store the Ente vault key" 0 bash -c "printf 'ENTE_KEY_PLAINTEXT' | '$BIN' ente-session put --token '$TOKEN_HUMAN' --json"
165
179
  grep -q 'ENTE_KEY_PLAINTEXT' "$AI_VAULT_DIR/ente.session.json" && bad "the ente key is plaintext on disk" || ok "the ente key is sealed at rest"
166
180
  [[ "$(mode_of "$AI_VAULT_DIR/ente.session.json")" == "600" ]] && ok "ente.session.json is 0600" || bad "ente.session.json is not 0600"
167
181
  "$BIN" ente-session get --json | grep -q 'ENTE_KEY_PLAINTEXT' && ok "ente-session get unseals it" || bad "ente-session get cannot unseal"
168
- "$BIN" settings ente.unlock session --json >/dev/null
182
+ setting ente.unlock session >/dev/null
169
183
  check "switching back to session clears the ente key" 5 "$BIN" ente-session get
170
184
 
171
185
  echo "== item types =="
@@ -212,6 +226,37 @@ PY
212
226
  relay Note y >"$TMP/note" 2>&1; [[ $? -eq 0 ]] && ok "get returns a secure note's body" || bad "get of a note failed"
213
227
  grep -q 'body: hunter2' "$TMP/note" && ok "the note body is in notes" || bad "note body missing"
214
228
 
229
+ echo "== the settings cannot be edited on disk =="
230
+ [[ -f "$AI_VAULT_DIR/config.json" ]] && bad "a plaintext config.json exists" || ok "no plaintext config.json: the settings live inside the store's ciphertext"
231
+ grep -q '"confirm"' "$AI_VAULT_DIR/store.json" && bad "settings are readable in store.json" || ok "settings are not readable in store.json"
232
+ # The attack: a config.json that turns the per-read window off. It is picked
233
+ # up at the next unlock as a legacy file — minus anything that lowers
234
+ # protection, so the attack gains nothing.
235
+ echo '{"vault":{"unlock":"session","hours":8,"confirm":false}}' >"$AI_VAULT_DIR/config.json"
236
+ TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
237
+ setting vault.confirm --token "$TKH" >"$TMP/c2"
238
+ [[ "$(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"
239
+ [[ -f "$AI_VAULT_DIR/config.json" ]] && bad "config.json still there" || ok "the legacy file was removed after migration"
240
+ echo '{"vault":{"unlock":"never","hours":8,"confirm":true}}' >"$AI_VAULT_DIR/config.json"
241
+ 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 "")')
242
+ setting vault.unlock --token "$TKH" >"$TMP/c2b"
243
+ [[ "$(setting_value "$TMP/c2b")" == "session" ]] && ok "the legacy file's unlock=never did not make it in either" || bad "unlock=never was migrated from the file"
244
+ # Flipping one byte of the store (where the settings now live) is a tamper.
245
+ cp "$AI_VAULT_DIR/store.json" "$TMP/store.bak"
246
+ python3 -c "
247
+ import json,base64;p='$AI_VAULT_DIR/store.json';d=json.load(open(p));ct=bytearray(base64.b64decode(d['ct']));ct[-1]^=1;d['ct']=base64.b64encode(bytes(ct)).decode();json.dump(d,open(p,'w'))"
248
+ check "a byte flipped in the store is rejected" 5 bash -c "printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' unlock --password-stdin"
249
+ cp "$TMP/store.bak" "$AI_VAULT_DIR/store.json"
250
+ # Turning the window off the real way costs the master password.
251
+ TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
252
+ check "confirm off with a wrong password is refused" 5 bash -c "printf 'wrong\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' settings vault.confirm false --password-stdin --token '$TKH'"
253
+ setting vault.confirm false --token "$TKH" >"$TMP/c3"
254
+ setting vault.confirm --token "$TKH" >"$TMP/c3v"
255
+ [[ "$(setting_value "$TMP/c3v")" == "false" ]] && ok "confirm off with the right password" || bad "confirm could not be turned off"
256
+ setting vault.confirm true --token "$TKH" >"$TMP/c4"
257
+ setting vault.confirm --token "$TKH" >"$TMP/c4v"
258
+ [[ "$(setting_value "$TMP/c4v")" == "true" ]] && ok "turning it back on needs no password" || bad "confirm could not be turned back on"
259
+
215
260
  echo "== rekey (L2) =="
216
261
  OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
217
262
  check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
@@ -234,10 +279,9 @@ PY
234
279
  grep -q 'p1ssw0rd' "$AI_VAULT_DIR/audit.log" && bad "a secret reached the audit log" || ok "no secret in audit.log"
235
280
 
236
281
  echo "== unlock modes =="
237
- check "mode get works without a token" 0 "$BIN" mode --json
238
- check "switching the mode needs the password" 3 "$BIN" mode set never
239
- check "a wrong password does not switch it" 5 bash -c "printf 'wrong password' | '$BIN' mode set never --password-stdin"
240
- check "never mode is set with the password" 0 bash -c "printf 'correct horse' | '$BIN' mode set never --password-stdin --json"
282
+ check "mode get works with a session" 0 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' mode --password-stdin --token '$TOKEN_HUMAN' --json"
283
+ check "a wrong password does not switch it" 5 bash -c "printf 'wrong password\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' mode set never --password-stdin --token '$TOKEN_HUMAN'"
284
+ check "never mode is set with the password" 0 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' mode set never --password-stdin --token '$TOKEN_HUMAN' --json"
241
285
  check "never mode needs no token" 0 "$BIN" status --json
242
286
  printf 'correct horse' | "$BIN" unlock --password-stdin --json >"$TMP/u2" 2>&1
243
287
  python3 - "$TMP/u2" <<'PY' && ok "unlock reports the mode" || bad "unlock output is wrong"
@@ -245,29 +289,29 @@ import json,sys
245
289
  d = json.load(open(sys.argv[1]))
246
290
  assert d["mode"] == "never" and d["auto"] is True, d
247
291
  PY
248
- check "back to session mode" 0 bash -c "printf 'correct horse' | '$BIN' mode set session --password-stdin --json"
292
+ 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"
249
293
  check "session mode needs a token again" 5 "$BIN" status
250
294
 
251
295
  echo "== settings =="
252
- check "settings prints everything" 0 "$BIN" settings --json
253
- check "set bitwarden.import" 0 "$BIN" settings bitwarden.import never --json
254
- "$BIN" settings bitwarden.import --json >"$TMP/set1"
296
+ 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"
297
+ check "set bitwarden.import" 0 setting bitwarden.import never
298
+ setting bitwarden.import >"$TMP/set1"
255
299
  python3 - "$TMP/set1" <<'PY' && ok "the import policy was stored" || bad "the import policy was not stored"
256
300
  import json,sys
257
301
  assert json.load(open(sys.argv[1]))["value"] == "never"
258
302
  PY
259
- check "an unknown setting is a usage error" 2 "$BIN" settings nope.value 1
260
- check "bw-session put is refused in session mode" 1 bash -c "printf 'K' | '$BIN' bw-session put"
261
- check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
262
- check "bw-session put stores the key" 0 bash -c "printf 'GOOD_SESSION' | '$BIN' bw-session put --json"
303
+ check "an unknown setting is a usage error" 2 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' unlock --password-stdin --json | python3 -c 'import json,sys;print(json.load(sys.stdin)[\"token\"])' >'$TMP/tk'; printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' settings nope.value 1 --password-stdin --token \"\$(cat '$TMP/tk')\""
304
+ check "bw-session put is refused in session mode" 1 bash -c "printf 'K' | '$BIN' bw-session put --token '$TOKEN_HUMAN'"
305
+ check "switch bitwarden.unlock to never" 0 setting bitwarden.unlock never
306
+ check "bw-session put stores the key" 0 bash -c "printf 'GOOD_SESSION' | '$BIN' bw-session put --token '$TOKEN_HUMAN' --json"
263
307
  [[ "$(mode_of "$AI_VAULT_DIR/bitwarden.session.json")" == "600" ]] && ok "the bw session file is 0600" || bad "the bw session file is not 0600"
264
308
  check "bw-session get returns it" 0 "$BIN" bw-session get --json
265
- check "switch back to session" 0 "$BIN" settings bitwarden.unlock session --json
309
+ check "switch back to session" 0 setting bitwarden.unlock session
266
310
  check "the stored key is gone" 5 "$BIN" bw-session get
267
- check "bitwarden.unlock time keeps an expiry" 0 "$BIN" settings bitwarden.unlock time --json
268
- check "bw-session put in time mode" 0 bash -c "printf 'K2' | '$BIN' bw-session put --json"
311
+ check "bitwarden.unlock time keeps an expiry" 0 setting bitwarden.unlock time
312
+ check "bw-session put in time mode" 0 bash -c "printf 'K2' | '$BIN' bw-session put --token '$TOKEN_HUMAN' --json"
269
313
  grep -q '"expiresAt": *[0-9]' "$AI_VAULT_DIR/bitwarden.session.json" && ok "time mode writes a deadline" || bad "time mode wrote no deadline"
270
- "$BIN" settings bitwarden.unlock session --json >/dev/null
314
+ setting bitwarden.unlock session >/dev/null
271
315
 
272
316
  echo "== two stores share the sessions dir =="
273
317
  # A second store in another directory uses the same XDG_RUNTIME_DIR sessions
@@ -1,9 +1,12 @@
1
- import { test } from "node:test";
1
+ import { test, before } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { readFileSync, writeFileSync, rmSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { spawnSync } from "node:child_process";
6
- import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, textOf, useMocks } from "./helpers.mjs";
6
+ import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, setSetting, textOf, useMocks } from "./helpers.mjs";
7
+ const { settingsToken, settingsCli } = await import("../packages/pi-ai-vault/src/settings.ts");
8
+ /** The extension's one HostSecret, as env for a CLI call made on its behalf. */
9
+ const hostSecretFor = () => settingsCli().host.value;
7
10
 
8
11
  const { forgetSettings } = await import("../packages/pi-ai-vault/src/settings.ts");
9
12
 
@@ -11,6 +14,14 @@ const dir = useMocks();
11
14
  const { default: aiVault } = await import("../packages/pi-ai-vault/src/index.ts");
12
15
  cleanUpOnExit(dir);
13
16
 
17
+ // The settings live inside the store now, so changing one needs an
18
+ // initialised store — the same throwaway one the vault tests use.
19
+ before(async () => {
20
+ answers.master(dir, "correct horse battery", "correct horse battery");
21
+ const boot = bind(aiVault, true);
22
+ await boot.cmd("init", makeCtx().ctx);
23
+ });
24
+
14
25
  const enteLog = () => {
15
26
  try {
16
27
  return readFileSync(join(dir, "ente.log"), "utf8");
@@ -98,7 +109,7 @@ const enteEnv = () => {
98
109
 
99
110
  test("session mode passes no vault key: the OS keychain stays in charge", async () => {
100
111
  const bin = process.env.AI_VAULT_BIN;
101
- spawnSync(bin, ["settings", "ente.unlock", "session"], { env: process.env });
112
+ setSetting("ente.unlock", "session");
102
113
  forgetSettings();
103
114
  const b = bind(aiVault, true);
104
115
  await b.tool("ente_list", {}, makeCtx().ctx);
@@ -107,9 +118,17 @@ test("session mode passes no vault key: the OS keychain stays in charge", async
107
118
 
108
119
  test("ente.unlock=never feeds the sealed key to the ente child", async () => {
109
120
  const bin = process.env.AI_VAULT_BIN;
110
- const set = spawnSync(bin, ["settings", "ente.unlock", "never"], { env: process.env, encoding: "utf8" });
121
+ const set = setSetting("ente.unlock", "never");
111
122
  assert.equal(set.status, 0, set.stderr);
112
- const put = spawnSync(bin, ["ente-session", "put"], { input: "MY_SECRET_VAULT_KEY", env: process.env, encoding: "utf8" });
123
+ // Unlock through the extension so the token is a host session (the put
124
+ // below is then made under the same secret).
125
+ answers.master(dir, "correct horse battery");
126
+ await bind(aiVault, true).cmd("unlock", makeCtx().ctx);
127
+ const put = spawnSync(bin, ["ente-session", "put", "--token", settingsToken() ?? ""], {
128
+ input: "MY_SECRET_VAULT_KEY",
129
+ env: { ...process.env, AI_VAULT_HOST: "1", AI_VAULT_HOST_SECRET: hostSecretFor() },
130
+ encoding: "utf8",
131
+ });
113
132
  assert.equal(put.status, 0, put.stderr);
114
133
  forgetSettings();
115
134
 
@@ -121,7 +140,7 @@ test("ente.unlock=never feeds the sealed key to the ente child", async () => {
121
140
 
122
141
  test("an inherited ENTE_CLI_VAULT_KEY is not trusted in session mode", async () => {
123
142
  const bin = process.env.AI_VAULT_BIN;
124
- spawnSync(bin, ["settings", "ente.unlock", "session"], { env: process.env });
143
+ setSetting("ente.unlock", "session");
125
144
  spawnSync(bin, ["ente-session", "clear"], { env: process.env });
126
145
  forgetSettings();
127
146
  const previous = process.env.ENTE_CLI_VAULT_KEY;
package/tests/helpers.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
- import { dirname, join } from "node:path";
6
+ import { delimiter, dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
 
9
9
  export const MOCKS = join(dirname(fileURLToPath(import.meta.url)), "mocks", "bin");
@@ -13,13 +13,14 @@ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
13
13
  export function cliBinary() {
14
14
  const explicit = process.env.AI_VAULT_BIN;
15
15
  if (explicit) return explicit;
16
+ const file = process.platform === "win32" ? "ai-vault.exe" : "ai-vault";
16
17
  for (const profile of ["release", "debug"]) {
17
- const candidate = join(ROOT, "target", profile, "ai-vault");
18
+ const candidate = join(ROOT, "target", profile, file);
18
19
  if (existsSync(candidate)) return candidate;
19
20
  }
20
21
  const built = spawnSync("cargo", ["build", "--release"], { cwd: ROOT, stdio: "inherit" });
21
22
  if (built.status !== 0) throw new Error("cannot build the ai-vault CLI; run `cargo build --release`");
22
- return join(ROOT, "target", "release", "ai-vault");
23
+ return join(ROOT, "target", "release", file);
23
24
  }
24
25
 
25
26
  /**
@@ -33,7 +34,7 @@ export function useMocks() {
33
34
  process.env.HOME = join(dir, "home");
34
35
  process.env.DISPLAY = ":99";
35
36
  delete process.env.WAYLAND_DISPLAY;
36
- process.env.PATH = `${MOCKS}:${process.env.PATH}`;
37
+ process.env.PATH = `${MOCKS}${delimiter}${process.env.PATH}`;
37
38
  process.env.OMP_VAULT_BW_MOCK_DIR = dir;
38
39
  process.env.OMP_VAULT_MOCK = dir;
39
40
  // The ente mock keeps its own state directory, like the bw one.
@@ -42,7 +43,7 @@ export function useMocks() {
42
43
  process.env.AI_VAULT_BIN = cliBinary();
43
44
  // The extension resolves the CLI from PATH; the tests pass one explicitly.
44
45
  // Put the same build first so both halves run the same version.
45
- process.env.PATH = `${dirname(process.env.AI_VAULT_BIN)}:${process.env.PATH}`;
46
+ process.env.PATH = `${dirname(process.env.AI_VAULT_BIN)}${delimiter}${process.env.PATH}`;
46
47
  return dir;
47
48
  }
48
49
 
@@ -134,3 +135,39 @@ export function bind(ompVault, omp = true) {
134
135
  }
135
136
 
136
137
  export const textOf = (result) => result.content.find((block) => block.type === "text")?.text ?? "";
138
+
139
+ /** A fresh human session token for the throwaway store, or undefined. */
140
+ export function unlockToken() {
141
+ const run = spawnSync(process.env.AI_VAULT_BIN, ["unlock", "--password-stdin", "--json"], {
142
+ input: "correct horse battery\n",
143
+ env: process.env,
144
+ encoding: "utf8",
145
+ });
146
+ return run.status === 0 ? JSON.parse(run.stdout).token : undefined;
147
+ }
148
+
149
+ /**
150
+ * Change an ai-vault setting the way a host does: with a session token, and
151
+ * with the master password on stdin for the changes that lower protection
152
+ * (confirm off, unlock never, import always …). Returns the CLI result.
153
+ */
154
+ export function setSetting(key, value, { password } = {}) {
155
+ // The extension caches settings for 30s; a change made here must be seen.
156
+ process.emit("ai-vault:settings-changed");
157
+ const bin = process.env.AI_VAULT_BIN;
158
+ const run = spawnSync(bin, ["unlock", "--password-stdin", "--json"], {
159
+ input: `${password ?? "correct horse battery"}\n`,
160
+ env: process.env,
161
+ encoding: "utf8",
162
+ });
163
+ // In `never` mode the unlock refreshes the machine-wide session and the
164
+ // caller is expected to use no token at all (that is what `auto: true`
165
+ // means); a per-session token is not minted there.
166
+ const unlocked = run.status === 0 ? JSON.parse(run.stdout) : undefined;
167
+ const token = unlocked && !unlocked.auto ? unlocked.token : undefined;
168
+ return spawnSync(bin, ["settings", key, value, "--password-stdin", ...(token ? ["--token", token] : [])], {
169
+ input: `${password ?? "correct horse battery"}\n`,
170
+ env: process.env,
171
+ encoding: "utf8",
172
+ });
173
+ }
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { existsSync } from "node:fs";
5
5
  import { join } from "node:path";
6
- import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, subCtx, textOf, useMocks } from "./helpers.mjs";
6
+ import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, setSetting, subCtx, textOf, useMocks } from "./helpers.mjs";
7
7
 
8
8
  // The extension is only a client: these drive the real ai-vault binary (built
9
9
  // by `npm test`) plus the mock zenity, with a throwaway store.
@@ -188,29 +188,22 @@ test("a denied Bitwarden read is not retried", async () => {
188
188
 
189
189
  test("never mode reads without any window, and the switch needs the password", async () => {
190
190
  const bin = process.env.AI_VAULT_BIN;
191
- const switchMode = (mode) =>
192
- spawnSync(bin, ["mode", "set", mode, "--password-stdin"], {
193
- input: `${PW}\n`,
194
- env: process.env,
195
- encoding: "utf8",
196
- });
191
+ // `mode set` reads and writes the settings inside the store: it needs an
192
+ // unlocked session (the helper opens one) and the master password.
193
+ const switchMode = (mode) => setSetting("vault.unlock", mode);
197
194
  const toNever = switchMode("never");
198
- assert.equal(toNever.status, 0, toNever.stderr);
195
+ assert.equal(toNever.status, 0, "set never: " + toNever.stderr + " | env HOST=" + process.env.AI_VAULT_HOST + " SECRET=" + (process.env.AI_VAULT_HOST_SECRET ? "set" : "unset"));
199
196
 
200
197
  const b = bind(aiVault, true);
201
198
  const ctx = makeCtx().ctx;
202
199
  const before = prompts("--question") + prompts("--password");
203
200
  const result = await b.tool("vault_get", { name: "GitHub" }, ctx);
204
- assert.equal(result.details.via, "no-password");
201
+ assert.equal(result.details.via, "no-password", textOf(result));
205
202
  assert.match(textOf(result), /pw-one/);
206
203
  assert.equal(prompts("--question") + prompts("--password"), before, "no window in never mode");
207
204
 
208
205
  // A wrong password must not change the policy.
209
- const wrong = spawnSync(bin, ["mode", "set", "session", "--password-stdin"], {
210
- input: "definitely-wrong\n",
211
- env: process.env,
212
- encoding: "utf8",
213
- });
206
+ const wrong = setSetting("vault.unlock", "session", { password: "definitely-wrong" });
214
207
  assert.equal(wrong.status, 5);
215
208
 
216
209
  const back = switchMode("session");
@@ -219,7 +212,7 @@ test("never mode reads without any window, and the switch needs the password", a
219
212
 
220
213
  test("bitwarden.import=never reads once with a single window", async () => {
221
214
  const bin = process.env.AI_VAULT_BIN;
222
- spawnSync(bin, ["settings", "bitwarden.import", "never"], { env: process.env });
215
+ setSetting("bitwarden.import", "never");
223
216
  forgetSettings();
224
217
  const b = bind(aiVault, true);
225
218
  const ctx = makeCtx().ctx;
@@ -235,7 +228,7 @@ test("bitwarden.import=never reads once with a single window", async () => {
235
228
 
236
229
  test("bitwarden.import=always pulls the entry in without a window", async () => {
237
230
  const bin = process.env.AI_VAULT_BIN;
238
- spawnSync(bin, ["settings", "bitwarden.import", "always"], { env: process.env });
231
+ setSetting("bitwarden.import", "always");
239
232
  forgetSettings();
240
233
  const b = bind(aiVault, true);
241
234
  const ctx = makeCtx().ctx;
@@ -253,16 +246,24 @@ test("bitwarden.import=always pulls the entry in without a window", async () =>
253
246
  JSON.parse(textOf(listed)).some((i) => i.name === "OtherService"),
254
247
  true,
255
248
  );
256
- spawnSync(bin, ["settings", "bitwarden.import", "ask"], { env: process.env });
249
+ setSetting("bitwarden.import", "ask");
257
250
  forgetSettings();
258
251
  });
259
252
 
260
253
  test("a persisted Bitwarden session costs no password", async () => {
261
254
  const bin = process.env.AI_VAULT_BIN;
262
- const set = (key, value) => spawnSync(bin, ["settings", key, value], { env: process.env, encoding: "utf8" });
255
+ const set = (key, value) => setSetting(key, value);
263
256
  assert.equal(set("bitwarden.unlock", "never").status, 0);
264
257
  forgetSettings();
265
- const put = spawnSync(bin, ["bw-session", "put"], { input: "GOOD_SESSION", env: process.env, encoding: "utf8" });
258
+ answers.master(dir, PW);
259
+ await bind(aiVault, true).cmd("unlock", makeCtx().ctx);
260
+ const { settingsToken: st, settingsCli: sc } = await import("../packages/pi-ai-vault/src/settings.ts");
261
+ forgetSettings();
262
+ const put = spawnSync(bin, ["bw-session", "put", "--token", st() ?? ""], {
263
+ input: "GOOD_SESSION",
264
+ env: { ...process.env, AI_VAULT_HOST: "1", AI_VAULT_HOST_SECRET: sc().host.value },
265
+ encoding: "utf8",
266
+ });
266
267
  assert.equal(put.status, 0, put.stderr);
267
268
 
268
269
  const b = bind(aiVault, true);
@@ -369,3 +370,4 @@ test("vault_get falls back to Bitwarden for a non-login hit and imports it with
369
370
  assert.equal(card.fields.cardholderName, "Li Jun");
370
371
  assert.equal(JSON.stringify(listed).includes("4111111111111111"), false, "list must mask the card number");
371
372
  });
373
+