@icoretech/warden-mcp 0.2.13 → 0.2.15

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/dist/bw/bwCli.js CHANGED
@@ -13,6 +13,37 @@ export class BwCliError extends Error {
13
13
  this.stderr = opts.stderr;
14
14
  }
15
15
  }
16
+ export function isBwAuthSessionInvalidError(error) {
17
+ if (!(error instanceof BwCliError))
18
+ return false;
19
+ const combined = [error.stderr, error.stdout, error.message]
20
+ .join('\n')
21
+ .toLowerCase();
22
+ if (/not found/.test(combined) ||
23
+ /more than one result/.test(combined) ||
24
+ /multiple results/.test(combined) ||
25
+ /ambiguous/.test(combined) ||
26
+ /invalid search/.test(combined) ||
27
+ /could not connect/.test(combined) ||
28
+ /connection/.test(combined) ||
29
+ /network/.test(combined) ||
30
+ /timeout/.test(combined) ||
31
+ /timed out/.test(combined) ||
32
+ /server error/.test(combined)) {
33
+ return false;
34
+ }
35
+ return (/invalid\s+(bw\s+)?session/.test(combined) ||
36
+ /(bw\s+)?session\s+(is\s+)?invalid/.test(combined) ||
37
+ /expired\s+(bw\s+)?session/.test(combined) ||
38
+ /(bw\s+)?session\s+(has\s+)?expired/.test(combined) ||
39
+ /not logged in/.test(combined) ||
40
+ /not authenticated/.test(combined) ||
41
+ /you are not authenticated/.test(combined) ||
42
+ /vault is locked/.test(combined) ||
43
+ /please unlock/.test(combined) ||
44
+ /unlock your vault/.test(combined) ||
45
+ /requires an unlocked vault/.test(combined));
46
+ }
16
47
  export async function runBw(args, opts = {}) {
17
48
  const bwBin = process.env.BW_BIN ?? resolveBundledBwBin() ?? 'bw';
18
49
  // Ensure the CLI never blocks waiting for a prompt (e.g. master password).
@@ -1,7 +1,7 @@
1
1
  // src/bw/bwSession.ts
2
2
  import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { runBw } from './bwCli.js';
4
+ import { isBwAuthSessionInvalidError, runBw } from './bwCli.js';
5
5
  import { Mutex } from './mutex.js';
6
6
  const POST_LOGIN_UNLOCK_RETRY_ATTEMPTS = 20;
7
7
  const POST_LOGIN_UNLOCK_RETRY_DELAY_MS = 2_000;
@@ -50,6 +50,7 @@ export class BwSessionManager {
50
50
  session = null;
51
51
  templateItem = null;
52
52
  keepaliveTimer = null;
53
+ warmupPromise = null;
53
54
  configuredHost = null;
54
55
  homeDir;
55
56
  appDataDir;
@@ -108,7 +109,16 @@ export class BwSessionManager {
108
109
  async withSession(fn) {
109
110
  return this.lock.runExclusive(async () => {
110
111
  const session = await this.ensureUnlockedInternal();
111
- return fn(session);
112
+ try {
113
+ return await fn(session);
114
+ }
115
+ catch (error) {
116
+ if (!isBwAuthSessionInvalidError(error))
117
+ throw error;
118
+ await this.clearSessionStateLocked();
119
+ const refreshedSession = await this.ensureUnlockedInternal();
120
+ return fn(refreshedSession);
121
+ }
112
122
  });
113
123
  }
114
124
  async getTemplateItem() {
@@ -142,10 +152,29 @@ export class BwSessionManager {
142
152
  : this.env.login.method === 'userpass'
143
153
  ? this.env.login.user
144
154
  : null;
145
- const isUnlocked = rawStatus === 'unlocked';
155
+ let isUnlocked = rawStatus === 'unlocked';
156
+ if (!isUnlocked) {
157
+ if (this.session && (await this.isSessionValid(this.session))) {
158
+ isUnlocked = true;
159
+ }
160
+ else {
161
+ const storedSession = await this.readStoredSessionState();
162
+ if (storedSession?.session &&
163
+ (await this.isSessionValid(storedSession.session))) {
164
+ this.session = storedSession.session;
165
+ await this.writeStoredSessionState(storedSession.session);
166
+ isUnlocked = true;
167
+ }
168
+ }
169
+ }
170
+ if (rawStatus === 'locked') {
171
+ this.startBackgroundUnlock();
172
+ }
146
173
  const summaryParts = isUnlocked
147
174
  ? ['Vault access ready']
148
- : ['Vault access not ready'];
175
+ : [
176
+ 'Vault access not ready yet; this lazy status check does not unlock the vault, but keychain tools will attempt unlock/recovery on demand',
177
+ ];
149
178
  if (userEmail)
150
179
  summaryParts.push(`for ${userEmail}`);
151
180
  if (serverUrl)
@@ -156,6 +185,10 @@ export class BwSessionManager {
156
185
  operational: {
157
186
  ready: isUnlocked,
158
187
  sessionValid: isUnlocked,
188
+ recoverable: !isUnlocked,
189
+ nextAction: isUnlocked
190
+ ? 'continue'
191
+ : 'call a keychain tool such as search_items or get_username to initialize vault access on demand',
159
192
  source: 'session_manager',
160
193
  },
161
194
  };
@@ -168,11 +201,14 @@ export class BwSessionManager {
168
201
  env: this.baseEnv(opts.env),
169
202
  });
170
203
  }
171
- async resetCliProfile() {
204
+ async clearSessionStateLocked() {
172
205
  this.session = null;
173
206
  this.templateItem = null;
174
- this.configuredHost = null;
175
207
  await this.clearStoredSessionState();
208
+ }
209
+ async resetCliProfile() {
210
+ await this.clearSessionStateLocked();
211
+ this.configuredHost = null;
176
212
  await runBw(['logout'], { env: this.baseEnv(), timeoutMs: 30_000 }).catch(() => { });
177
213
  const home = this.homeDir;
178
214
  const cliStateDirs = [
@@ -269,7 +305,10 @@ export class BwSessionManager {
269
305
  'BW_PASSWORD',
270
306
  '--raw',
271
307
  ], { env: unlockEnv, timeoutMs: 60_000, noInteraction: false });
272
- return { completed: true, session: stdout.trim() };
308
+ const session = stdout.trim();
309
+ if (!session)
310
+ return { completed: false, session: '' };
311
+ return { completed: true, session };
273
312
  }
274
313
  catch {
275
314
  return { completed: false, session: '' };
@@ -314,6 +353,15 @@ export class BwSessionManager {
314
353
  return session;
315
354
  });
316
355
  }
356
+ startBackgroundUnlock() {
357
+ if (this.session || this.warmupPromise)
358
+ return;
359
+ this.warmupPromise = this.withSession(async () => undefined)
360
+ .catch(() => { })
361
+ .finally(() => {
362
+ this.warmupPromise = null;
363
+ });
364
+ }
317
365
  sessionIdentity() {
318
366
  return this.env.login.method === 'apikey'
319
367
  ? `apikey:${this.env.login.clientId}`
@@ -2,7 +2,7 @@
2
2
  import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { basename, join } from 'node:path';
5
- import { BwCliError } from '../bw/bwCli.js';
5
+ import { BwCliError, isBwAuthSessionInvalidError } from '../bw/bwCli.js';
6
6
  import { deepClone } from './clone.js';
7
7
  import { buildBwGenerateArgs } from './generateArgs.js';
8
8
  import { applyItemPatch } from './patch.js';
@@ -68,6 +68,30 @@ function denormalizeUris(raw) {
68
68
  }
69
69
  return out;
70
70
  }
71
+ function isUsernameLookupFailure(error) {
72
+ const combined = [error.stderr, error.stdout, error.message]
73
+ .join('\n')
74
+ .toLowerCase();
75
+ if (/could not connect/.test(combined) ||
76
+ /connection/.test(combined) ||
77
+ /network/.test(combined) ||
78
+ /timeout/.test(combined) ||
79
+ /timed out/.test(combined) ||
80
+ /server error/.test(combined) ||
81
+ /internal server error/.test(combined) ||
82
+ /bad gateway/.test(combined) ||
83
+ /service unavailable/.test(combined)) {
84
+ return false;
85
+ }
86
+ return (/not found/.test(combined) ||
87
+ /no item/.test(combined) ||
88
+ /no matching/.test(combined) ||
89
+ /more than one result/.test(combined) ||
90
+ /multiple results/.test(combined) ||
91
+ /ambiguous/.test(combined) ||
92
+ /invalid search/.test(combined) ||
93
+ /invalid lookup/.test(combined));
94
+ }
71
95
  function kindFromItem(item) {
72
96
  const type = item.type;
73
97
  if (type === ITEM_TYPE.login)
@@ -927,9 +951,46 @@ export class KeychainSdk {
927
951
  }
928
952
  /** Always reveals — username is not considered a secret by Bitwarden. */
929
953
  async getUsername(input) {
954
+ const term = input.term.trim();
955
+ if (!term)
956
+ throw new Error('Username lookup term is empty');
930
957
  return this.bw.withSession(async (session) => {
931
- const { stdout } = await this.bw.runForSession(session, ['--raw', 'get', 'username', input.term], { timeoutMs: 60_000 });
932
- return this.valueResult(stdout.trim(), true);
958
+ try {
959
+ const { stdout } = await this.bw.runForSession(session, ['--raw', 'get', 'username', term], { timeoutMs: 60_000 });
960
+ const username = stdout.trim();
961
+ if (!username)
962
+ throw new Error('Username lookup found an empty username');
963
+ return this.valueResult(username, true);
964
+ }
965
+ catch (error) {
966
+ if (isBwAuthSessionInvalidError(error))
967
+ throw error;
968
+ if (!(error instanceof BwCliError) || error.exitCode !== 1)
969
+ throw error;
970
+ if (!isUsernameLookupFailure(error))
971
+ throw error;
972
+ const { stdout } = await this.bw.runForSession(session, ['list', 'items', '--search', term], { timeoutMs: 120_000 });
973
+ const rawResults = this.parseBwJson(stdout);
974
+ const candidates = rawResults.filter((raw) => !!raw &&
975
+ typeof raw === 'object' &&
976
+ raw.type === ITEM_TYPE.login);
977
+ if (candidates.length === 0) {
978
+ throw new Error('Username lookup failed: no login item found');
979
+ }
980
+ const exactCandidates = candidates.filter((item) => this.candidateMatchesTerm(item, [term]));
981
+ const narrowed = exactCandidates.length > 0 ? exactCandidates : candidates;
982
+ if (narrowed.length !== 1) {
983
+ throw new Error('Username lookup failed: multiple matching login items found');
984
+ }
985
+ const login = narrowed[0]?.login && typeof narrowed[0].login === 'object'
986
+ ? narrowed[0].login
987
+ : null;
988
+ const username = login?.username;
989
+ if (typeof username !== 'string' || username.trim().length === 0) {
990
+ throw new Error('Username lookup found an empty username');
991
+ }
992
+ return this.valueResult(username.trim(), true);
993
+ }
933
994
  });
934
995
  }
935
996
  /** Requires opts.reveal=true; returns {value: null, revealed: false} when ungated. */
@@ -108,7 +108,7 @@ export function registerTools(server, deps) {
108
108
  }
109
109
  registerTool(`${deps.toolPrefix}.status`, {
110
110
  title: 'Vault Status',
111
- description: 'Returns Bitwarden CLI status (locked/unlocked, server, user).',
111
+ description: 'Returns Bitwarden CLI status (locked/unlocked, server, user). This is a lazy check: not-ready status does not mean later keychain tool calls cannot unlock or recover on demand.',
112
112
  annotations: { readOnlyHint: true },
113
113
  inputSchema: {},
114
114
  _meta: toolMeta,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@icoretech/warden-mcp",
4
- "version": "0.2.13",
4
+ "version": "0.2.15",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "Vaultwarden/Bitwarden MCP server backed by Bitwarden CLI (bw).",
@@ -49,10 +49,10 @@
49
49
  "zod": "^4.3.6"
50
50
  },
51
51
  "optionalDependencies": {
52
- "@bitwarden/cli": "2026.3.0"
52
+ "@bitwarden/cli": "2026.4.1"
53
53
  },
54
54
  "devDependencies": {
55
- "@biomejs/biome": "^2.4.12",
55
+ "@biomejs/biome": "^2.4.13",
56
56
  "@types/express": "^5.0.6",
57
57
  "@types/node": "^25.6.0",
58
58
  "playwright": "1.59.1",