@icoretech/warden-mcp 0.2.64 → 0.2.65

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
@@ -20,6 +20,12 @@ export class BwCliError extends Error {
20
20
  this.diagnosticCode = opts.diagnosticCode ?? null;
21
21
  }
22
22
  }
23
+ export class BwCliStdinError extends Error {
24
+ constructor() {
25
+ super('Failed to write input to bw CLI');
26
+ this.name = 'BwCliStdinError';
27
+ }
28
+ }
23
29
  function diagnoseBwCliFailure(stderr) {
24
30
  if (stderr.includes('Error getting vault timeout: RangeError: Invalid time value') &&
25
31
  stderr.includes('no elements in sequence')) {
@@ -77,15 +83,12 @@ export async function runBw(args, opts = {}) {
77
83
  env,
78
84
  stdio: ['pipe', 'pipe', 'pipe'],
79
85
  detached,
86
+ windowsHide: true,
80
87
  });
81
88
  const stdoutChunks = [];
82
89
  const stderrChunks = [];
83
90
  child.stdout.on('data', (d) => stdoutChunks.push(d));
84
91
  child.stderr.on('data', (d) => stderrChunks.push(d));
85
- if (opts.stdin !== undefined) {
86
- child.stdin.write(opts.stdin);
87
- }
88
- child.stdin.end();
89
92
  const timeoutMs = opts.timeoutMs ?? 60_000;
90
93
  const killChildProcessTree = () => {
91
94
  if (typeof child.pid === 'number' && detached) {
@@ -110,6 +113,10 @@ export async function runBw(args, opts = {}) {
110
113
  };
111
114
  return new Promise((resolve, reject) => {
112
115
  let settled = false;
116
+ let stdinFailed = false;
117
+ child.stdin.on('error', () => {
118
+ stdinFailed = true;
119
+ });
113
120
  const settle = (fn) => {
114
121
  if (settled)
115
122
  return;
@@ -159,11 +166,16 @@ export async function runBw(args, opts = {}) {
159
166
  }));
160
167
  return;
161
168
  }
169
+ if (stdinFailed) {
170
+ reject(new BwCliStdinError());
171
+ return;
172
+ }
162
173
  if (debug) {
163
174
  console.log(`[bw] ok: ms=${Date.now() - startedAt}`);
164
175
  }
165
176
  resolve({ stdout, stdoutBuffer: Buffer.concat(stdoutChunks), stderr });
166
177
  });
167
178
  });
179
+ child.stdin.end(opts.stdin);
168
180
  });
169
181
  }
@@ -0,0 +1,71 @@
1
+ import { z } from 'zod';
2
+ const credentialsSchema = z.object({
3
+ host: z.string().min(1),
4
+ password: z.string().min(1),
5
+ login: z.discriminatedUnion('method', [
6
+ z.object({
7
+ method: z.literal('apikey'),
8
+ clientId: z.string().min(1),
9
+ clientSecret: z.string().min(1),
10
+ }),
11
+ z.object({ method: z.literal('userpass'), user: z.string().min(1) }),
12
+ ]),
13
+ });
14
+ export class BwCredentialError extends Error {
15
+ constructor() {
16
+ super('Bitwarden credential provider failed or returned mismatched credentials');
17
+ this.name = 'BwCredentialError';
18
+ }
19
+ }
20
+ function assertNever(_login) {
21
+ throw new BwCredentialError();
22
+ }
23
+ export function sessionConfig(env) {
24
+ return {
25
+ host: env.host,
26
+ unlockIntervalSeconds: env.unlockIntervalSeconds,
27
+ homeDir: env.homeDir,
28
+ login: env.login.method === 'apikey'
29
+ ? { method: 'apikey', clientId: env.login.clientId }
30
+ : { method: 'userpass', user: env.login.user },
31
+ };
32
+ }
33
+ export function staticCredentialProvider(env) {
34
+ const parsed = credentialsSchema.safeParse(env);
35
+ if (!parsed.success)
36
+ throw new BwCredentialError();
37
+ const credentials = { ...sessionConfig(env), ...parsed.data };
38
+ return () => credentials;
39
+ }
40
+ export async function loadCredentials(config, provider) {
41
+ let supplied;
42
+ try {
43
+ supplied = await provider();
44
+ }
45
+ catch {
46
+ // Provider failures are an untrusted boundary; never preserve their cause.
47
+ throw new BwCredentialError();
48
+ }
49
+ const parsed = credentialsSchema.safeParse(supplied);
50
+ if (!parsed.success || parsed.data.host !== config.host) {
51
+ throw new BwCredentialError();
52
+ }
53
+ const credentials = parsed.data;
54
+ switch (config.login.method) {
55
+ case 'apikey':
56
+ if (credentials.login.method !== 'apikey' ||
57
+ credentials.login.clientId !== config.login.clientId) {
58
+ throw new BwCredentialError();
59
+ }
60
+ break;
61
+ case 'userpass':
62
+ if (credentials.login.method !== 'userpass' ||
63
+ credentials.login.user !== config.login.user) {
64
+ throw new BwCredentialError();
65
+ }
66
+ break;
67
+ default:
68
+ return assertNever(config.login);
69
+ }
70
+ return { ...config, ...credentials };
71
+ }
@@ -1,28 +1,40 @@
1
1
  import { isBwAuthSessionInvalidError, runBw } from './bwCli.js';
2
+ import { sessionConfig, staticCredentialProvider } from './bwCredentials.js';
2
3
  import { BwSessionAuth } from './bwSessionAuth.js';
3
4
  import { Mutex } from './mutex.js';
5
+ export { BwCredentialError } from './bwCredentials.js';
4
6
  export { readBwEnv } from './bwEnv.js';
7
+ export { BwSessionRevokeError } from './bwSessionRevocation.js';
5
8
  export class BwSessionManager {
6
- env;
7
9
  lock = new Mutex();
8
10
  auth;
9
11
  templateItem = null;
10
12
  keepaliveTimer = null;
11
13
  warmupPromise = null;
12
- constructor(env) {
13
- this.env = env;
14
- this.auth = new BwSessionAuth(env, () => {
14
+ env;
15
+ backgroundAuthEnabled;
16
+ backgroundGeneration = 0;
17
+ backgroundAuthSuspended = false;
18
+ constructor(env, options = {}) {
19
+ this.env = sessionConfig(env);
20
+ this.backgroundAuthEnabled =
21
+ options.persistSession !== false &&
22
+ options.credentialProvider === undefined;
23
+ this.auth = new BwSessionAuth(this.env, () => {
15
24
  this.templateItem = null;
16
- });
25
+ }, options.credentialProvider ?? staticCredentialProvider(env), options.persistSession ?? true);
17
26
  }
18
27
  startKeepUnlocked() {
19
- if (this.keepaliveTimer)
28
+ if (!this.backgroundAuthEnabled || this.keepaliveTimer)
20
29
  return;
30
+ const generation = this.backgroundGeneration;
21
31
  const intervalMs = Math.max(10, this.env.unlockIntervalSeconds) * 1000;
22
32
  this.keepaliveTimer = setInterval(() => {
23
33
  if (!this.auth.hasSession())
24
34
  return;
25
35
  void this.lock.runExclusive(async () => {
36
+ if (generation !== this.backgroundGeneration || !this.auth.hasSession())
37
+ return;
26
38
  try {
27
39
  await this.auth.ensureUnlocked();
28
40
  }
@@ -58,6 +70,18 @@ export class BwSessionManager {
58
70
  return this.getTemplateItemLocked(session);
59
71
  }
60
72
  async status() {
73
+ const generation = this.backgroundGeneration;
74
+ return this.lock.runExclusive(() => this.statusLocked(generation));
75
+ }
76
+ async revoke() {
77
+ this.backgroundGeneration += 1;
78
+ this.backgroundAuthSuspended = true;
79
+ if (this.keepaliveTimer)
80
+ clearInterval(this.keepaliveTimer);
81
+ this.keepaliveTimer = null;
82
+ await this.lock.runExclusive(() => this.auth.revoke());
83
+ }
84
+ async statusLocked(generation) {
61
85
  const { stdout } = await runBw(['status'], {
62
86
  env: this.auth.storage.baseEnv(),
63
87
  timeoutMs: 60_000,
@@ -79,7 +103,7 @@ export class BwSessionManager {
79
103
  const isUnlocked = rawStatus === 'unlocked' ||
80
104
  (await this.auth.hasValidSessionWithoutUnlock());
81
105
  if (rawStatus === 'locked')
82
- this.startBackgroundUnlock();
106
+ this.startBackgroundUnlock(generation);
83
107
  const summaryParts = isUnlocked
84
108
  ? ['Vault access ready']
85
109
  : [
@@ -104,15 +128,15 @@ export class BwSessionManager {
104
128
  };
105
129
  }
106
130
  async runForSession(session, args, opts = {}) {
107
- return runBw(['--session', session, ...args], {
131
+ return runBw(args, {
108
132
  ...opts,
109
- env: this.auth.storage.baseEnv(opts.env),
133
+ env: this.auth.storage.baseEnv({ ...opts.env, BW_SESSION: session }),
110
134
  });
111
135
  }
112
136
  async getTemplateItemLocked(session) {
113
137
  if (this.templateItem)
114
138
  return this.templateItem;
115
- const { stdout } = await runBw(['--session', session, 'get', 'template', 'item'], { env: this.auth.storage.baseEnv(), timeoutMs: 60_000 });
139
+ const { stdout } = await this.runForSession(session, ['get', 'template', 'item'], { timeoutMs: 60_000 });
116
140
  try {
117
141
  this.templateItem = JSON.parse(stdout);
118
142
  return this.templateItem;
@@ -121,10 +145,19 @@ export class BwSessionManager {
121
145
  throw new Error(`Failed to parse bw template output (${stdout.length} bytes)`, { cause: error });
122
146
  }
123
147
  }
124
- startBackgroundUnlock() {
125
- if (this.auth.hasSession() || this.warmupPromise)
148
+ startBackgroundUnlock(generation) {
149
+ if (!this.backgroundAuthEnabled ||
150
+ this.backgroundAuthSuspended ||
151
+ generation !== this.backgroundGeneration ||
152
+ this.auth.hasSession() ||
153
+ this.warmupPromise)
126
154
  return;
127
- this.warmupPromise = this.withSession(async () => undefined)
155
+ this.warmupPromise = this.lock
156
+ .runExclusive(async () => {
157
+ if (generation !== this.backgroundGeneration)
158
+ return;
159
+ await this.auth.ensureUnlocked();
160
+ })
128
161
  .catch(() => { })
129
162
  .finally(() => {
130
163
  this.warmupPromise = null;
@@ -1,4 +1,6 @@
1
1
  import { runBw } from './bwCli.js';
2
+ import { loadCredentials } from './bwCredentials.js';
3
+ import { revokeProfile } from './bwSessionRevocation.js';
2
4
  import { BwSessionStorage } from './bwSessionStorage.js';
3
5
  const POST_LOGIN_UNLOCK_RETRY_ATTEMPTS = 20;
4
6
  const POST_LOGIN_UNLOCK_RETRY_DELAY_MS = 2_000;
@@ -8,17 +10,19 @@ function sleep(ms) {
8
10
  export class BwSessionAuth {
9
11
  env;
10
12
  onSessionCleared;
13
+ credentialProvider;
11
14
  storage;
12
15
  session = null;
13
16
  configuredHost = null;
14
- constructor(env, onSessionCleared) {
17
+ constructor(env, onSessionCleared, credentialProvider, persistSession = true) {
15
18
  this.env = env;
16
19
  this.onSessionCleared = onSessionCleared;
20
+ this.credentialProvider = credentialProvider;
17
21
  const homeDir = env.homeDir ?? process.env.HOME ?? '/data';
18
22
  const identity = env.login.method === 'apikey'
19
23
  ? `apikey:${env.login.clientId}`
20
24
  : `userpass:${env.login.user}`;
21
- this.storage = new BwSessionStorage(homeDir, env.host, identity);
25
+ this.storage = new BwSessionStorage(homeDir, env.host, identity, persistSession);
22
26
  }
23
27
  hasSession() {
24
28
  return this.session !== null;
@@ -45,11 +49,12 @@ export class BwSessionAuth {
45
49
  }
46
50
  await this.storage.clearSession();
47
51
  }
48
- let session = await this.obtainSession();
52
+ const credentials = await loadCredentials(this.env, this.credentialProvider);
53
+ let session = await this.obtainSession(credentials);
49
54
  if (!session) {
50
55
  await this.resetCliProfile();
51
56
  await this.ensureServerConfigured();
52
- session = await this.obtainSession();
57
+ session = await this.obtainSession(credentials);
53
58
  }
54
59
  if (!session) {
55
60
  throw new Error('bw login/unlock returned an empty session');
@@ -72,9 +77,16 @@ export class BwSessionAuth {
72
77
  currentSession() {
73
78
  return this.session;
74
79
  }
80
+ async revoke() {
81
+ this.clearInMemorySession();
82
+ await revokeProfile(this.storage);
83
+ }
75
84
  async isSessionValid(session) {
76
85
  try {
77
- const { stdout } = await runBw(['--session', session, 'unlock', '--check'], { env: this.storage.baseEnv(), timeoutMs: 30_000 });
86
+ const { stdout } = await runBw(['unlock', '--check'], {
87
+ env: this.storage.baseEnv({ BW_SESSION: session }),
88
+ timeoutMs: 30_000,
89
+ });
78
90
  void stdout;
79
91
  return true;
80
92
  }
@@ -82,11 +94,11 @@ export class BwSessionAuth {
82
94
  return false;
83
95
  }
84
96
  }
85
- async tryUnlock() {
97
+ async tryUnlock(credentials) {
86
98
  try {
87
99
  const { stdout } = await runBw(['unlock', '--passwordenv', 'BW_PASSWORD', '--raw'], {
88
100
  env: this.storage.baseEnv({
89
- BW_PASSWORD: this.env.password,
101
+ BW_PASSWORD: credentials.password,
90
102
  BW_HOST: this.env.host,
91
103
  }),
92
104
  timeoutMs: 60_000,
@@ -98,13 +110,13 @@ export class BwSessionAuth {
98
110
  return '';
99
111
  }
100
112
  }
101
- async tryLogin() {
113
+ async tryLogin(credentials) {
102
114
  try {
103
- if (this.env.login.method === 'apikey') {
115
+ if (credentials.login.method === 'apikey') {
104
116
  const { stdout } = await runBw(['login', '--apikey', '--raw'], {
105
117
  env: this.storage.baseEnv({
106
- BW_CLIENTID: this.env.login.clientId,
107
- BW_CLIENTSECRET: this.env.login.clientSecret,
118
+ BW_CLIENTID: credentials.login.clientId,
119
+ BW_CLIENTSECRET: credentials.login.clientSecret,
108
120
  BW_HOST: this.env.host,
109
121
  }),
110
122
  timeoutMs: 60_000,
@@ -112,9 +124,15 @@ export class BwSessionAuth {
112
124
  });
113
125
  return { completed: true, session: stdout.trim() };
114
126
  }
115
- const { stdout } = await runBw(['login', this.env.login.user, '--passwordenv', 'BW_PASSWORD', '--raw'], {
127
+ const { stdout } = await runBw([
128
+ 'login',
129
+ credentials.login.user,
130
+ '--passwordenv',
131
+ 'BW_PASSWORD',
132
+ '--raw',
133
+ ], {
116
134
  env: this.storage.baseEnv({
117
- BW_PASSWORD: this.env.password,
135
+ BW_PASSWORD: credentials.password,
118
136
  BW_HOST: this.env.host,
119
137
  }),
120
138
  timeoutMs: 60_000,
@@ -127,9 +145,9 @@ export class BwSessionAuth {
127
145
  return { completed: false, session: '' };
128
146
  }
129
147
  }
130
- async retryUnlockAfterLogin() {
148
+ async retryUnlockAfterLogin(credentials) {
131
149
  for (let attempt = 0; attempt < POST_LOGIN_UNLOCK_RETRY_ATTEMPTS; attempt += 1) {
132
- const session = await this.tryUnlock();
150
+ const session = await this.tryUnlock(credentials);
133
151
  if (session)
134
152
  return session;
135
153
  if (attempt < POST_LOGIN_UNLOCK_RETRY_ATTEMPTS - 1) {
@@ -138,19 +156,19 @@ export class BwSessionAuth {
138
156
  }
139
157
  return '';
140
158
  }
141
- async obtainSession() {
142
- let session = await this.tryUnlock();
159
+ async obtainSession(credentials) {
160
+ let session = await this.tryUnlock(credentials);
143
161
  if (!session) {
144
- const login = await this.tryLogin();
162
+ const login = await this.tryLogin(credentials);
145
163
  if (login.session) {
146
164
  session = login.session;
147
165
  }
148
166
  else if (login.completed) {
149
- session = await this.retryUnlockAfterLogin();
167
+ session = await this.retryUnlockAfterLogin(credentials);
150
168
  }
151
169
  }
152
170
  if (!session)
153
- session = await this.tryUnlock();
171
+ session = await this.tryUnlock(credentials);
154
172
  return session;
155
173
  }
156
174
  async resetCliProfile() {
@@ -0,0 +1,38 @@
1
+ import { runBw } from './bwCli.js';
2
+ export class BwSessionRevokeError extends Error {
3
+ failures;
4
+ constructor(failures) {
5
+ super(`Bitwarden session revocation failed (${failures.join(', ')})`);
6
+ this.name = 'BwSessionRevokeError';
7
+ this.failures = [...failures];
8
+ }
9
+ }
10
+ export async function revokeProfile(storage) {
11
+ try {
12
+ await storage.withAuthLock(async () => {
13
+ const failures = [];
14
+ try {
15
+ await storage.deleteSession();
16
+ }
17
+ catch {
18
+ failures.push('cache');
19
+ }
20
+ try {
21
+ await runBw(['lock'], {
22
+ env: storage.baseEnv(),
23
+ timeoutMs: 30_000,
24
+ });
25
+ }
26
+ catch {
27
+ failures.push('lock');
28
+ }
29
+ if (failures.length > 0)
30
+ throw new BwSessionRevokeError(failures);
31
+ });
32
+ }
33
+ catch (error) {
34
+ if (error instanceof BwSessionRevokeError)
35
+ throw error;
36
+ throw new BwSessionRevokeError(['profile']);
37
+ }
38
+ }
@@ -38,13 +38,15 @@ function isProcessAlive(pid) {
38
38
  export class BwSessionStorage {
39
39
  host;
40
40
  identity;
41
+ persistSession;
41
42
  homeDir;
42
43
  appDataDir;
43
44
  processLockDir;
44
45
  sessionStatePath;
45
- constructor(homeDir, host, identity) {
46
+ constructor(homeDir, host, identity, persistSession = true) {
46
47
  this.host = host;
47
48
  this.identity = identity;
49
+ this.persistSession = persistSession;
48
50
  this.homeDir = homeDir;
49
51
  this.appDataDir = join(homeDir, '.bitwarden-cli');
50
52
  this.processLockDir = join(this.appDataDir, '.warden-mcp-auth-lock');
@@ -82,6 +84,8 @@ export class BwSessionStorage {
82
84
  }
83
85
  }
84
86
  async readSession() {
87
+ if (!this.persistSession)
88
+ return null;
85
89
  try {
86
90
  await chmod(this.sessionStatePath, 0o600);
87
91
  const raw = await readFile(this.sessionStatePath, 'utf8');
@@ -100,6 +104,8 @@ export class BwSessionStorage {
100
104
  }
101
105
  }
102
106
  async writeSession(session) {
107
+ if (!this.persistSession)
108
+ return;
103
109
  const now = new Date().toISOString();
104
110
  const state = {
105
111
  version: 1,
@@ -120,8 +126,13 @@ export class BwSessionStorage {
120
126
  }
121
127
  }
122
128
  async clearSession() {
129
+ if (!this.persistSession)
130
+ return;
123
131
  await rm(this.sessionStatePath, { force: true }).catch(() => { });
124
132
  }
133
+ async deleteSession() {
134
+ await rm(this.sessionStatePath, { force: true });
135
+ }
125
136
  async clearCliDataFiles() {
126
137
  const stateDirs = [
127
138
  this.appDataDir,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@icoretech/warden-mcp",
4
- "version": "0.2.64",
4
+ "version": "0.2.65",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "Vaultwarden/Bitwarden MCP server backed by Bitwarden CLI (bw).",
@@ -30,6 +30,7 @@
30
30
  "dist/",
31
31
  "bin/",
32
32
  "!dist/**/*.test.js",
33
+ "!dist/**/*.fixture.js",
33
34
  "!dist/integration/"
34
35
  ],
35
36
  "scripts": {