@xiaolikt/ai-vault 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,19 +169,94 @@ 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
 
185
+ echo "== item types =="
186
+ # The tamper block consumed the earlier host token; open a fresh host session.
187
+ HOST_JSON=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json)
188
+ TOKEN=$(printf '%s' "$HOST_JSON" | json token)
189
+ cat >"$TMP/all-types.json" <<'JSON'
190
+ {"items":[
191
+ {"id":"t1","type":1,"name":"Login","login":{"username":"u","password":"gh-pw","totp":"JBSWY3DP"},"fields":[{"name":"API_KEY","value":"hf_sk_abc987xyz456","type":1},{"name":"Plan","value":"Team","type":0}]},
192
+ {"id":"t2","type":2,"name":"Note","secureNote":{},"notes":"body: hunter2"},
193
+ {"id":"t3","type":3,"name":"Card","card":{"cardholderName":"Li","brand":"Visa","number":"4111111111111111","expMonth":"12","expYear":"2029","code":"123"}},
194
+ {"id":"t4","type":4,"name":"Identity","identity":{"firstName":"Jun","ssn":"123-45-6789","licenseNumber":"DL-99"}},
195
+ {"id":"t5","type":5,"name":"Key","sshKey":{"privateKey":"PEM-PRIVATE","publicKey":"ssh-ed25519 PUB"}},
196
+ {"id":"t6","type":6,"name":"Bank","bankAccount":{"bankName":"ICBC","accountNumber":"6222000011112222","pin":"9080"}},
197
+ {"id":"t7","type":7,"name":"Licence","driversLicense":{"licenseNumber":"110101"}},
198
+ {"id":"t8","type":8,"name":"Passport","passport":{"passportNumber":"E1234567","nationality":"CN"}}
199
+ ]}
200
+ JSON
201
+ check "import every item type" 0 "$BIN" import "$TMP/all-types.json" --yes --token "$TOKEN" --json
202
+ "$BIN" list --token "$TOKEN" --json >"$TMP/typed-list"
203
+ python3 - "$TMP/typed-list" <<'PY' && ok "list carries the type of each entry" || bad "list does not carry types"
204
+ import json,sys
205
+ items = json.load(open(sys.argv[1]))["items"]
206
+ types = {i["name"]: i["type"] for i in items}
207
+ for name, kind in {"Login":"login","Note":"secureNote","Card":"card","Identity":"identity","Key":"sshKey","Bank":"bankAccount","Licence":"driversLicense","Passport":"passport"}.items():
208
+ assert types.get(name) == kind, (name, types.get(name))
209
+ PY
210
+ for secret in gh-pw hunter2 4111111111111111 123-45-6789 DL-99 hf_sk_abc987xyz456 PEM-PRIVATE 6222000011112222 110101 E1234567 JBSWY3DP; do
211
+ grep -q "$secret" "$TMP/typed-list" && bad "list leaked $secret"
212
+ done
213
+ ok "list masks passwords, card number and code, keys, PIN, account and document numbers, hidden fields, TOTP seeds"
214
+ grep -q '"hasNotes":true' "$TMP/typed-list" && ok "list flags which entries carry notes" || bad "hasNotes missing"
215
+ # a manual entry of a non-login type, secret typed (stdin here for the primary field)
216
+ check "add a card by hand with --type and --field" 0 bash -c "printf '999\n' | '$BIN' add --name HandCard --type card --field brand=Amex --field cardholderName='Li Jun' --field expYear=2031 --field number=378282246310005 --password-stdin --yes --token '$TOKEN' --json"
217
+ check "a wrong field name is refused" 2 "$BIN" add --name X --type card --field cvv=1 --yes --token "$TOKEN"
218
+ check "a wrong type name is refused" 2 "$BIN" add --name X --type wifi --yes --token "$TOKEN"
219
+ check "--secret rejects a non-secret field" 2 bash -c "'$BIN' add --name X --type card --field brand=Visa --secret brand=Visa --secret code=1 --yes --token '$TOKEN'"
220
+ relay Card y >"$TMP/card" 2>&1; [[ $? -eq 0 ]] && ok "get returns a card with its data block" || bad "get of a card failed"
221
+ python3 - "$TMP/card" <<'PY' && ok "get shows the type's fields by Bitwarden's names" || bad "get output is wrong"
222
+ import json,sys
223
+ d = json.load(open(sys.argv[1]))
224
+ assert d["type"] == "card" and d["data"]["code"] == "123" and d["data"]["number"] == "4111111111111111", d
225
+ PY
226
+ relay Note y >"$TMP/note" 2>&1; [[ $? -eq 0 ]] && ok "get returns a secure note's body" || bad "get of a note failed"
227
+ grep -q 'body: hunter2' "$TMP/note" && ok "the note body is in notes" || bad "note body missing"
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
+
171
260
  echo "== rekey (L2) =="
172
261
  OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
173
262
  check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
@@ -190,10 +279,9 @@ PY
190
279
  grep -q 'p1ssw0rd' "$AI_VAULT_DIR/audit.log" && bad "a secret reached the audit log" || ok "no secret in audit.log"
191
280
 
192
281
  echo "== unlock modes =="
193
- check "mode get works without a token" 0 "$BIN" mode --json
194
- check "switching the mode needs the password" 3 "$BIN" mode set never
195
- check "a wrong password does not switch it" 5 bash -c "printf 'wrong password' | '$BIN' mode set never --password-stdin"
196
- 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"
197
285
  check "never mode needs no token" 0 "$BIN" status --json
198
286
  printf 'correct horse' | "$BIN" unlock --password-stdin --json >"$TMP/u2" 2>&1
199
287
  python3 - "$TMP/u2" <<'PY' && ok "unlock reports the mode" || bad "unlock output is wrong"
@@ -201,29 +289,29 @@ import json,sys
201
289
  d = json.load(open(sys.argv[1]))
202
290
  assert d["mode"] == "never" and d["auto"] is True, d
203
291
  PY
204
- 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"
205
293
  check "session mode needs a token again" 5 "$BIN" status
206
294
 
207
295
  echo "== settings =="
208
- check "settings prints everything" 0 "$BIN" settings --json
209
- check "set bitwarden.import" 0 "$BIN" settings bitwarden.import never --json
210
- "$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"
211
299
  python3 - "$TMP/set1" <<'PY' && ok "the import policy was stored" || bad "the import policy was not stored"
212
300
  import json,sys
213
301
  assert json.load(open(sys.argv[1]))["value"] == "never"
214
302
  PY
215
- check "an unknown setting is a usage error" 2 "$BIN" settings nope.value 1
216
- check "bw-session put is refused in session mode" 1 bash -c "printf 'K' | '$BIN' bw-session put"
217
- check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
218
- 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"
219
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"
220
308
  check "bw-session get returns it" 0 "$BIN" bw-session get --json
221
- check "switch back to session" 0 "$BIN" settings bitwarden.unlock session --json
309
+ check "switch back to session" 0 setting bitwarden.unlock session
222
310
  check "the stored key is gone" 5 "$BIN" bw-session get
223
- check "bitwarden.unlock time keeps an expiry" 0 "$BIN" settings bitwarden.unlock time --json
224
- 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"
225
313
  grep -q '"expiresAt": *[0-9]' "$AI_VAULT_DIR/bitwarden.session.json" && ok "time mode writes a deadline" || bad "time mode wrote no deadline"
226
- "$BIN" settings bitwarden.unlock session --json >/dev/null
314
+ setting bitwarden.unlock session >/dev/null
227
315
 
228
316
  echo "== two stores share the sessions dir =="
229
317
  # A second store in another directory uses the same XDG_RUNTIME_DIR sessions
@@ -175,8 +175,8 @@ test("a denied confirmation never fetches the entry; an approved one fetches it
175
175
 
176
176
  // An id is looked up in the listing, so a wrong one fails before any window.
177
177
  await assert.rejects(
178
- b.tool("bw_run", { item: "cccc3333-3333-4333-8333-333333333333", command: "true" }),
179
- /No Bitwarden item with id cccc3333/,
178
+ b.tool("bw_run", { item: "ffff9999-9999-4999-8999-999999999999", command: "true" }),
179
+ /No Bitwarden item with id ffff9999/,
180
180
  );
181
181
  });
182
182
 
@@ -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
+ }
@@ -1,22 +1,23 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { bitwardenLogins, filterLogins } from "../packages/pi-ai-vault/src/import-map.ts";
3
+ import { bitwardenItems, filterItems, isSecretField, parseItemType } from "../packages/pi-ai-vault/src/import-map.ts";
4
4
 
5
- const item = (name, extra = {}) => ({
5
+ const login = (name, extra = {}) => ({
6
6
  id: extra.id,
7
+ type: 1,
7
8
  name,
8
9
  login: { username: extra.username, password: extra.password ?? "pw-value-1", uris: extra.uri ? [{ uri: extra.uri }] : [] },
9
10
  notes: extra.notes,
11
+ fields: extra.fields,
10
12
  });
11
13
 
12
14
  test("reads a Bitwarden export object and a raw array", () => {
13
- const fromExport = bitwardenLogins({
14
- items: [item("GitHub", { username: "me", uri: "https://github.com", notes: "n" })],
15
- });
16
- const fromArray = bitwardenLogins([item("GitHub", { username: "me", uri: "https://github.com", notes: "n" })]);
15
+ const fromExport = bitwardenItems({ items: [login("GitHub", { username: "me", uri: "https://github.com", notes: "n" })] });
16
+ const fromArray = bitwardenItems([login("GitHub", { username: "me", uri: "https://github.com", notes: "n" })]);
17
17
  assert.equal(fromExport.length, 1);
18
18
  assert.deepEqual(fromExport[0], {
19
19
  name: "GitHub",
20
+ type: "login",
20
21
  username: "me",
21
22
  password: "pw-value-1",
22
23
  uris: ["https://github.com"],
@@ -25,50 +26,86 @@ test("reads a Bitwarden export object and a raw array", () => {
25
26
  assert.deepEqual(fromArray, fromExport);
26
27
  });
27
28
 
29
+ test("every item type maps field for field, by Bitwarden's names", () => {
30
+ const drafts = bitwardenItems({
31
+ items: [
32
+ { id: "n", type: 2, name: "Wifi", secureNote: {}, notes: "guest: hunter2" },
33
+ { id: "c", type: 3, name: "Visa", card: { cardholderName: "Li", brand: "Visa", number: "4111", expMonth: "12", expYear: "2029", code: "123" } },
34
+ { id: "i", type: 4, name: "Me", identity: { title: "Mr", firstName: "Jun", lastName: "Li", ssn: "123-45-6789" } },
35
+ { id: "k", type: 5, name: "key", sshKey: { privateKey: "PEM", publicKey: "ssh-ed25519 AAA", keyFingerprint: "SHA256:x" } },
36
+ { id: "b", type: 6, name: "Bank", bankAccount: { bankName: "ICBC", accountNumber: "6222", pin: "9080", iban: null } },
37
+ { id: "d", type: 7, name: "Licence", driversLicense: { licenseNumber: "110101", expirationDate: "2030-01-01" } },
38
+ { id: "p", type: 8, name: "Passport", passport: { passportNumber: "E123", nationality: "CN" } },
39
+ ],
40
+ });
41
+ const byName = Object.fromEntries(drafts.map((d) => [d.name, d]));
42
+ assert.equal(byName.Wifi.type, "secureNote");
43
+ assert.equal(byName.Wifi.notes, "guest: hunter2");
44
+ assert.equal(byName.Wifi.data, undefined, "a secure note has no fields of its own");
45
+ assert.deepEqual(byName.Visa.data, { cardholderName: "Li", brand: "Visa", number: "4111", expMonth: "12", expYear: "2029", code: "123" });
46
+ assert.equal(byName.Me.data.ssn, "123-45-6789");
47
+ assert.equal(byName["key"].data.privateKey, "PEM");
48
+ assert.deepEqual(byName.Bank.data, { bankName: "ICBC", accountNumber: "6222", pin: "9080" }, "a null field is dropped");
49
+ assert.equal(byName.Licence.data.licenseNumber, "110101");
50
+ assert.equal(byName.Passport.data.passportNumber, "E123");
51
+ assert.equal(byName.Me.password, undefined, "only a login carries the flat password mirror");
52
+ });
53
+
54
+ test("custom fields keep their Bitwarden type, so a hidden one stays hidden", () => {
55
+ const [draft] = bitwardenItems([login("GH", { fields: [{ name: "API_KEY", value: "hf_abc", type: 1 }, { name: "Plan", value: "Team", type: 0 }] })]);
56
+ assert.deepEqual(draft.fields, [
57
+ { name: "API_KEY", value: "hf_abc", type: 1 },
58
+ { name: "Plan", value: "Team", type: 0 },
59
+ ]);
60
+ });
61
+
28
62
  test("each entry keeps the id of the Bitwarden item it came from", () => {
29
- const [draft] = bitwardenLogins({ items: [item("Cloud", { id: "bw-1", username: "root" })] });
63
+ const [draft] = bitwardenItems({ items: [login("Cloud", { id: "bw-1", username: "root" })] });
30
64
  assert.deepEqual(draft.source, { kind: "bitwarden", id: "bw-1" });
31
65
  });
32
66
 
33
67
  test("an encrypted export is refused instead of importing nothing", () => {
34
- assert.throws(
35
- () => bitwardenLogins({ encrypted: true, encKeyValidation: "…", data: "2.0|…" }),
36
- /encrypted Bitwarden export/,
37
- );
68
+ assert.throws(() => bitwardenItems({ encrypted: true, encKeyValidation: "…", data: "2.0|…" }), /encrypted Bitwarden export/);
38
69
  });
39
70
 
40
71
  test("a payload that is neither an export nor an item array is refused", () => {
41
- assert.throws(() => bitwardenLogins({ hello: "world" }), /Not a Bitwarden export/);
42
- assert.throws(() => bitwardenLogins(null), /Not a Bitwarden export/);
72
+ assert.throws(() => bitwardenItems({ hello: "world" }), /Not a Bitwarden export/);
73
+ assert.throws(() => bitwardenItems(null), /Not a Bitwarden export/);
43
74
  });
44
75
 
45
- test("skips items with no login password and blank names", () => {
46
- const drafts = bitwardenLogins({
47
- items: [
48
- { name: "note-only", notes: "x" },
49
- { name: "empty-login", login: { username: "a", password: "" } },
50
- { name: " \n", login: { password: "pw-value-1" } },
51
- ],
52
- });
53
- assert.equal(drafts.length, 1);
54
- assert.equal(drafts[0].name, "unnamed");
76
+ test("an unknown type number is an error, a blank name becomes 'unnamed'", () => {
77
+ assert.throws(() => bitwardenItems([{ type: 99, name: "x" }]), /unsupported Bitwarden item type 99/);
78
+ const [draft] = bitwardenItems([{ type: 1, name: " \n", login: { password: "p" } }]);
79
+ assert.equal(draft.name, "unnamed");
55
80
  });
56
81
 
57
- test("disambiguates duplicate names in a stable order", () => {
58
- const drafts = bitwardenLogins([item("GitHub", { username: "b" }), item("GitHub", { username: "a" }), item("Other", { username: "z" })]);
59
- assert.deepEqual(
60
- drafts.map((d) => `${d.name}|${d.username}`),
61
- ["GitHub|a", "GitHub (2)|b", "Other|z"],
62
- );
82
+ test("disambiguates duplicate names within a type, not across types", () => {
83
+ const drafts = bitwardenItems([login("GitHub", { username: "b" }), login("GitHub", { username: "a" }), { type: 2, name: "GitHub", secureNote: {} }]);
84
+ const names = drafts.map((d) => `${d.type}:${d.name}|${d.username ?? ""}`);
85
+ assert.deepEqual(names, ["login:GitHub|a", "login:GitHub (2)|b", "secureNote:GitHub|"]);
63
86
  });
64
87
 
65
- test("filter matches name, username, and uri", () => {
66
- const drafts = bitwardenLogins([
67
- item("GitHub", { username: "octo", uri: "https://github.com" }),
68
- item("Mail", { username: "me", uri: "https://mail.example" }),
69
- ]);
70
- assert.equal(filterLogins(drafts, "octo").length, 1);
71
- assert.equal(filterLogins(drafts, "mail.example")[0].name, "Mail");
72
- assert.equal(filterLogins(drafts, "nope").length, 0);
73
- assert.equal(filterLogins(drafts, " ").length, 2);
88
+ test("type names parse the way a human writes them", () => {
89
+ assert.equal(parseItemType(undefined), "login");
90
+ assert.equal(parseItemType("SSH key"), "sshKey");
91
+ assert.equal(parseItemType("secure-note"), "secureNote");
92
+ assert.equal(parseItemType("driver's licence"), "driversLicense");
93
+ assert.equal(parseItemType("wifi"), undefined);
94
+ });
95
+
96
+ test("secret fields are known per type", () => {
97
+ assert.equal(isSecretField("login", "password"), true);
98
+ assert.equal(isSecretField("card", "number"), true);
99
+ assert.equal(isSecretField("card", "brand"), false);
100
+ assert.equal(isSecretField("bankAccount", "pin"), true);
101
+ assert.equal(isSecretField("identity", "ssn"), true);
102
+ assert.equal(isSecretField("passport", "passportNumber"), true);
103
+ assert.equal(isSecretField("passport", "nationality"), false);
104
+ });
105
+
106
+ test("filterItems matches name, username, and URIs across every type", () => {
107
+ const items = bitwardenItems([login("GitHub", { username: "me", uri: "https://github.com" }), { type: 3, name: "Visa", card: { brand: "Visa" } }]);
108
+ assert.equal(filterItems(items, "visa")[0]?.name, "Visa");
109
+ assert.equal(filterItems(items, "github.com")[0]?.name, "GitHub");
110
+ assert.equal(filterItems(items).length, 2);
74
111
  });
@@ -30,11 +30,15 @@ case "$args" in
30
30
  fi ;;
31
31
  "sync --nointeraction") exit 0 ;;
32
32
  "list items --nointeraction")
33
- echo '[{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","totp":null,"uris":[{"uri":"https://test.example.com"}]},"notes":"note-secret-abc","fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]},{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]}]' ;;
33
+ echo '[{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","totp":null,"uris":[{"uri":"https://test.example.com"}]},"notes":"note-secret-abc","fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]},{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]},{"id":"cccc3333-3333-4333-8333-333333333333","type":3,"name":"CorpCard","card":{"cardholderName":"Li Jun","brand":"Visa","number":"4111111111111111","expMonth":"12","expYear":"2029","code":"123"}},{"id":"dddd4444-4444-4444-8444-444444444444","type":2,"name":"WifiNote","secureNote":{},"notes":"guest network: hunter2"}]' ;;
34
34
  "get item aaaa1111-1111-4111-8111-111111111111 --nointeraction")
35
35
  echo '{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","uris":[]},"fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]}' ;;
36
36
  "get item bbbb2222-2222-4222-8222-222222222222 --nointeraction")
37
37
  echo '{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]}' ;;
38
+ "get item cccc3333-3333-4333-8333-333333333333 --nointeraction")
39
+ echo '{"id":"cccc3333-3333-4333-8333-333333333333","type":3,"name":"CorpCard","card":{"cardholderName":"Li Jun","brand":"Visa","number":"4111111111111111","expMonth":"12","expYear":"2029","code":"123"}}' ;;
40
+ "get item dddd4444-4444-4444-8444-444444444444 --nointeraction")
41
+ echo '{"id":"dddd4444-4444-4444-8444-444444444444","type":2,"name":"WifiNote","secureNote":{},"notes":"guest network: hunter2"}' ;;
38
42
  "lock --nointeraction") touch "$MOCK_DIR/locked"; exit 0 ;;
39
43
  "get item "*" --nointeraction") echo "Not found." >&2; exit 1 ;;
40
44
  *) echo "mock bw: unhandled: $args" >&2; exit 1 ;;