@xiaolikt/ai-vault 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
@@ -134,3 +134,39 @@ export function bind(ompVault, omp = true) {
134
134
  }
135
135
 
136
136
  export const textOf = (result) => result.content.find((block) => block.type === "text")?.text ?? "";
137
+
138
+ /** A fresh human session token for the throwaway store, or undefined. */
139
+ export function unlockToken() {
140
+ const run = spawnSync(process.env.AI_VAULT_BIN, ["unlock", "--password-stdin", "--json"], {
141
+ input: "correct horse battery\n",
142
+ env: process.env,
143
+ encoding: "utf8",
144
+ });
145
+ return run.status === 0 ? JSON.parse(run.stdout).token : undefined;
146
+ }
147
+
148
+ /**
149
+ * Change an ai-vault setting the way a host does: with a session token, and
150
+ * with the master password on stdin for the changes that lower protection
151
+ * (confirm off, unlock never, import always …). Returns the CLI result.
152
+ */
153
+ export function setSetting(key, value, { password } = {}) {
154
+ // The extension caches settings for 30s; a change made here must be seen.
155
+ process.emit("ai-vault:settings-changed");
156
+ const bin = process.env.AI_VAULT_BIN;
157
+ const run = spawnSync(bin, ["unlock", "--password-stdin", "--json"], {
158
+ input: `${password ?? "correct horse battery"}\n`,
159
+ env: process.env,
160
+ encoding: "utf8",
161
+ });
162
+ // In `never` mode the unlock refreshes the machine-wide session and the
163
+ // caller is expected to use no token at all (that is what `auto: true`
164
+ // means); a per-session token is not minted there.
165
+ const unlocked = run.status === 0 ? JSON.parse(run.stdout) : undefined;
166
+ const token = unlocked && !unlocked.auto ? unlocked.token : undefined;
167
+ return spawnSync(bin, ["settings", key, value, "--password-stdin", ...(token ? ["--token", token] : [])], {
168
+ input: `${password ?? "correct horse battery"}\n`,
169
+ env: process.env,
170
+ encoding: "utf8",
171
+ });
172
+ }
@@ -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
+