#!/usr/bin/env node /** * bitwarden — MCP-Server fuer das Vaultwarden-Passworttresor (https://bitwarden.your-domain.com). * * Zweck: Jarvis liest, sucht und verwaltet Passwort-Eintraege des KONTOS * jarvis@your-domain.com (SSO-Login, Session/Unlock ueber config/mcp/.bw-masterpass). * * Sicherheitsmodell: * - Jeder bw-Befehl laeuft mit einem expliziten Session-Schluessel (BW_SESSION), den * der Server genau EINMAL nach Prozessstart oder nach einem Lock via * "bw unlock --raw --passwordfile " holt. Der Schluessel wird nur im * Speicher gehalten und nie geloggt/persistiert. * - bw_list_items/bw_search: KEINE Passwoerter/TOTP (nur Metadaten + Username/URI). * - bw_get_item: vollstaendiger Eintrag inkl. Passwort nur auf Anforderung * (include_secrets, Standard aus). * - create/update/delete: beabsichtigte Schreibzugriffe. Die Werte fuer den Server * werden als BASE64-JSON auf stdin uebergeben (bw 2025.x decodiert Base64); der * Server konstruiert das JSON selbst, nie aus Freitext-Befehlen. * - Passwörter und Session-Schluessel werden nie protokolliert; Ausgaben auf * MAX_CHARS begrenzt, hartes Timeout. */ 'use strict'; const { execFileSync } = require('child_process'); const fs = require('fs'); const TIMEOUT_MS = 20000; const MAX_CHARS = 50000; const MAX_ITEMS = 500; const DATA_DIR = process.env.BW_DATA_DIR || '/home/node/.openclaw/bw-data'; const CLI = process.env.BW_CLI || '/home/node/.openclaw/bw-cli/node_modules/@bitwarden/cli/build/bw.js'; const MP_FILE = process.env.BW_MP_FILE || '/home/node/.openclaw/mcp/.bw-masterpass'; const TYPE_NAMES = { 1: 'login', 2: 'secureNote', 3: 'card', 4: 'identity', 5: 'sshKey', 6: 'masterPassword' }; let sessionKey = null; function bwEnv(withSession) { const env = { ...process.env, BITWARDENCLI_APPDATA_DIR: DATA_DIR }; if (withSession && sessionKey) env.BW_SESSION = sessionKey; return env; } function runBw(args, input, withSession) { return execFileSync(CLI, args, { env: bwEnv(withSession !== false), input, timeout: TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], }).toString('utf8'); } function b64(s) { return Buffer.from(String(s), 'utf8').toString('base64'); } function readMasterpass() { let st; try { st = fs.statSync(MP_FILE); } catch (e) { return { error: `Master-Passwort-Datei nicht lesbar: ${MP_FILE}` }; } if ((st.mode & 0o077) !== 0) return { error: `Master-Passwort-Datei nicht restriktiv berechtigt (Modus ${st.mode & 0o777}).` }; if (st.uid !== 1000) return { error: `Master-Passwort-Datei gehoert uid ${st.uid}, erwartet 1000.` }; try { const t = fs.readFileSync(MP_FILE, 'utf8').trim(); if (!t) return { error: 'Master-Passwort-Datei ist leer.' }; return { password: t }; } catch (e) { return { error: 'Master-Passwort-Datei konnte nicht gelesen werden.' }; } } function statusNow() { try { const raw = runBw(['status']); return JSON.parse(raw); } catch (e) { return { status: sessionKey ? 'locked' : 'unreadable', error: String(e.message || e) }; } } function ensureSession() { if (sessionKey) { const s = statusNow(); if (s.status === 'unlocked') return { ok: true }; sessionKey = null; } const mp = readMasterpass(); if (mp.error) return { error: `Entsperren nicht moeglich: ${mp.error}` }; let key; try { key = runBw(['unlock', '--raw', '--passwordfile', MP_FILE], undefined, false).trim(); } catch (e) { return { error: `bw unlock fehlgeschlagen: ${String(e.stderr || e.message || e)}` }; } if (!key) return { error: 'bw unlock gab keinen Session-Schluessel zurueck.' }; sessionKey = key; const s = statusNow(); if (s.status !== 'unlocked') { sessionKey = null; return { error: `bw ist nach unlock nicht entsperrt (status=${s.status}).` }; } try { runBw(['sync']); } catch (e) { /* Sync-Fehler sind nicht kritisch */ } return { ok: true }; } function shortId(id) { return String(id || '').slice(0, 8); } function typeName(t) { return TYPE_NAMES[t] || String(t || '?'); } function relTime(iso) { if (!iso) return '-'; return String(iso).replace('T', ' ').replace('Z', 'U').slice(0, 16); } function sanitizeItem(i) { const login = i.login || {}; const uris = Array.isArray(login.uris) ? login.uris.map((u) => u.uri).filter(Boolean) : []; return { id: i.id, name: i.name || '(ohne Namen)', type: typeName(i.type), username: login.username || '', uris, favorite: Boolean(i.favorite), folderId: i.folderId || null, revisionDate: i.revisionDate || null, }; } function itemsJson() { const raw = runBw(['list', 'items']); const arr = JSON.parse(raw); return Array.isArray(arr) ? arr.filter((x) => x && x.id) : []; } function buildItemPayload(args) { const type = args.type || 'login'; const num = Number(Object.keys(TYPE_NAMES).find((k) => TYPE_NAMES[k] === type)); const p = { type: num || 1, name: String(args.name || ''), notes: args.notes || null, favorite: Boolean(args.favorite), folderId: args.folder_id || null }; if (type === 'login') { p.login = { username: args.username || '', password: args.password || '', uris: args.uris && args.uris.length ? args.uris.map((u) => ({ uri: u })) : [], }; } else if (type === 'secureNote') { p.secureNote = { type: 0 }; } return p; } const TOOLS = [ { name: 'bw_status', description: 'Zeigt den Zustand des Bitwarden/Vaultwarden-Logins: verbundener Server, Konto (E-Mail), Status unlocked/locked, Synchronisationszeit. Lesend.', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, }, { name: 'bw_list_items', description: 'Listet Vault-Eintraege aus dem lokalen Cache (Standard 50, max. 500). Nur Metadaten: Name, Typ, Benutzername, URIs, Favorit. KEINE Passwoerter. Optional nach Typ gefiltert. Lesend.', inputSchema: { type: 'object', properties: { type: { type: 'string', enum: ['login', 'secureNote', 'card', 'identity'], description: 'Nur Eintraege dieses Typs.' }, limit: { type: 'integer', description: 'Anzahl (1-500, Standard 50).' }, }, additionalProperties: false, }, }, { name: 'bw_search', description: 'Durchsucht Eintraege nach Text im Namen, Benutzernamen oder einer URI (Gross-/Kleinschreibung egal). Ergebnis als Metadaten-Tabelle ohne Passwoerter. Lesend.', inputSchema: { type: 'object', properties: { text: { type: 'string', description: 'Suchtext (Teilstring).' }, limit: { type: 'integer', description: 'Max. Treffer (1-100, Standard 20).' }, }, required: ['text'], additionalProperties: false, }, }, { name: 'bw_get_item', description: 'Liefert einen einzelnen Vault-Eintrag vollstaendig: Typ, Name, Notiz, Benutzername, URIs, benutzerdefinierte Felder. Mit include_secrets=true (Standard) zusaetzlich das Passwort bzw. TOTP-Secret. Lesend.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Eintrags-ID (ganz oder erste 8 Zeichen, z.B. "a9d9d037").' }, include_secrets: { type: 'boolean', description: 'Passwort/TOTP mitliefern (Standard true).' }, }, required: ['id'], additionalProperties: false, }, }, { name: 'bw_create_item', description: 'Legt einen neuen Vault-Eintrag an (Typ login oder secureNote). Bei login mit username/password und optional uris. Liefert die neue Eintrags-ID. SCHREIBEND.', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Anzeigename, z.B. "Externer Dienst".' }, type: { type: 'string', enum: ['login', 'secureNote'], description: 'Eintragstyp (Standard login).' }, username: { type: 'string', description: 'Bei login: Benutzername.' }, password: { type: 'string', description: 'Bei login: Passwort (bw_generate zum Erzeugen).' }, uris: { type: 'array', items: { type: 'string' }, description: 'Bei login: Webadresse(n).' }, folder_id: { type: 'string', description: 'Ordner-ID (optional; ohne wird "No Folder" verwendet).' }, notes: { type: 'string', description: 'Notiz (optional).' }, favorite: { type: 'boolean', description: 'Favorit (Standard false).' }, }, required: ['name'], additionalProperties: false, }, }, { name: 'bw_update_item', description: 'Aendert einen vorhandenen Vault-Eintrag. uebergib id plus die zu aendernden Felder; nicht genannte bleiben unveraendert. SCHREIBEND.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Eintrags-ID (ganz oder erste 8 Zeichen).' }, name: { type: 'string', description: 'Neuer Anzeigename.' }, type: { type: 'string', enum: ['login', 'secureNote'], description: 'Eintragstyp.' }, username: { type: 'string', description: 'Neuer Benutzername.' }, password: { type: 'string', description: 'Neues Passwort.' }, uris: { type: 'array', items: { type: 'string' }, description: 'Neue URI-Liste.' }, folder_id: { type: 'string', description: 'Neue Ordner-ID (leerer String = kein Ordner).' }, notes: { type: 'string', description: 'Neue Notiz.' }, favorite: { type: 'boolean', description: 'Favorit-Status.' }, }, required: ['id'], additionalProperties: false, }, }, { name: 'bw_delete_item', description: 'Loescht einen Vault-Eintrag unwiderruflich. VORHER mit bw_get_item bestaetigen, dass die richtige ID gewaehlt wurde. SCHREIBEND.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Eintrags-ID (ganz oder erste 8 Zeichen).' }, }, required: ['id'], additionalProperties: false, }, }, { name: 'bw_generate', description: 'Erzeugt ein starkes Zufallspasswort ueber bw generate (Laenge, Klein-/Gross-/Ziffern/Sonderzeichen, optional ohne mehrdeutige Zeichen; oder als Passphrase). Speichert NICHT in den Tresor. Lesend.', inputSchema: { type: 'object', properties: { length: { type: 'integer', description: 'Laenge (5-128, Standard 24).' }, upper: { type: 'boolean', description: 'Grossbuchstaben (Standard true).' }, lower: { type: 'boolean', description: 'Kleinbuchstaben (Standard true).' }, number: { type: 'boolean', description: 'Ziffern (Standard true).' }, special: { type: 'boolean', description: 'Sonderzeichen (Standard true).' }, ambiguous: { type: 'boolean', description: 'Mehrdeutige Zeichen (0/o/l/I/1) vermeiden (Standard false).' }, passphrase: { type: 'boolean', description: 'Stattdessen Passphrase erzeugen (Standard false).' }, }, additionalProperties: false, }, }, ]; async function bwStatus() { // Status is also the user's access check: refresh the in-memory session before // reporting locked, otherwise a fresh MCP process falsely looks disconnected. const session = ensureSession(); if (session.error) return { error: true, text: session.error }; const s = statusNow(); if (s.status === 'unreadable') return { error: true, text: `bw status nicht lesbar: ${s.error || ''}` }; const lines = [ '## Bitwarden/Vaultwarden', '', `- Server: ${s.serverUrl || '-'}`, `- Konto: ${s.userEmail || '-'} ${s.userId ? '(' + shortId(s.userId) + ')' : ''}`, `- Status: **${s.status === 'unlocked' ? 'entsperrt' : s.status}**`, `- Letzte Sync: ${relTime(s.lastSync)}`, ]; return { error: false, text: lines.join('\n') }; } async function listItems(args) { const u = ensureSession(); if (u.error) return { error: true, text: u.error }; let items; try { items = itemsJson(); } catch (e) { return { error: true, text: `Vault nicht lesbar: ${String(e.stderr || e.message || e)}` }; } const type = args && args.type; if (type) { const num = Object.keys(TYPE_NAMES).find((k) => TYPE_NAMES[k] === type); items = items.filter((i) => i.type === (num ? Number(num) : type)); } items.sort((a, b) => String(a.name || '').localeCompare(String(b.name || ''))); const limit = Math.min(500, Math.max(1, Number((args && args.limit) || 50))); const shown = items.slice(0, limit); const lines = [ '## Vault-Eintraege', '', `Gesamt: ${items.length}${items.length > shown.length ? `, angezeigt: ${shown.length}` : ''}`, '', '| ID | Typ | Name | Benutzer | URI | Festgelegt |', '|---|---|---|---|---|---|', ]; for (const s of shown.map(sanitizeItem)) { lines.push(`| ${shortId(s.id)} | ${s.type} | ${String(s.name).replace(/\|/g, '\\|')} | ${s.username || '-'} | ${(s.uris[0] || '-').replace(/\|/g, '\\|')} | ${s.favorite ? 'ja' : ''} |`); } lines.push('', `Passwoerter liefert bw_get_item mit der jeweiligen ID (${shortId(shown[0] ? shown[0].id : '')}...).`); return { error: false, text: lines.join('\n') }; } async function searchItems(args) { const u = ensureSession(); if (u.error) return { error: true, text: u.error }; const text = String((args && args.text) || '').trim().toLowerCase(); if (!text) return { error: true, text: 'Suchtext fehlt.' }; let items; try { items = itemsJson(); } catch (e) { return { error: true, text: `Vault nicht lesbar: ${String(e.stderr || e.message || e)}` }; } const hits = items .map(sanitizeItem) .filter((s) => { const hay = [s.name, s.username, ...s.uris].join(' ').toLowerCase(); return hay.indexOf(text) >= 0; }); hits.sort((a, b) => String(a.name).localeCompare(String(b.name))); const limit = Math.min(100, Math.max(1, Number((args && args.limit) || 20))); const shown = hits.slice(0, limit); const lines = [ '## Suche: ' + (args.text) + '', '', `Gefunden: ${hits.length}${hits.length > shown.length ? `, angezeigt: ${shown.length}` : ''}`, '', '| ID | Typ | Name | Benutzer | URI |', '|---|---|---|---|---|', ]; for (const s of shown) { lines.push(`| ${shortId(s.id)} | ${s.type} | ${String(s.name).replace(/\|/g, '\\|')} | ${s.username || '-'} | ${(s.uris[0] || '-').replace(/\|/g, '\\|')} |`); } if (!hits.length) lines.push('| (keine Treffer) |'); return { error: false, text: lines.join('\n') }; } async function getItem(args) { const u = ensureSession(); if (u.error) return { error: true, text: u.error }; const id = String((args && args.id) || '').trim(); if (!id) return { error: true, text: 'Eintrags-ID fehlt.' }; const wantSecrets = (args && args.include_secrets) !== false; let item; try { const raw = runBw(['get', 'item', id]); item = JSON.parse(raw); } catch (e) { return { error: true, text: `Eintrag ${id} nicht lesbar: ${String(e.stderr || e.message || e)}` }; } if (!item || item.error) return { error: true, text: `Eintrag ${id} nicht gefunden.` }; const login = item.login || {}; const lines = [ `## Eintrag ${item.name || '(ohne Namen)'}`, '', `- ID: ${item.id}`, `- Typ: ${typeName(item.type)}`, `- Ordner: ${item.folderId || '(kein)'}`, `- Favorit: ${item.favorite ? 'ja' : 'nein'}`, `- Erstellt: ${relTime(item.creationDate)}`, `- Geaendert: ${relTime(item.revisionDate)}`, ]; if (login.username) lines.push(`- Benutzer: ${login.username}`); const uris = Array.isArray(login.uris) ? login.uris.map((x) => x.uri).filter(Boolean) : []; if (uris.length) lines.push('- URIs: ' + uris.join(', ')); if (wantSecrets) { if (login.password) lines.push(`- **Passwort: \`${login.password}\`**`); if (login.totp) lines.push(`- TOTP: ${login.totp}`); } if (item.notes) lines.push('', '- Notiz:', '', String(item.notes).slice(0, MAX_CHARS)); const fields = Array.isArray(item.fields) ? item.fields.filter((f) => f && f.name) : []; if (fields.length) { lines.push('', '### Benutzerdefinierte Felder', ''); for (const f of fields) { const val = wantSecrets ? f.value : (f.type === 1 ? '**verborgen**' : f.value); lines.push(`- ${f.name}: ${val}`); } } return { error: false, text: lines.join('\n') }; } async function createItem(args) { const u = ensureSession(); if (u.error) return { error: true, text: u.error }; const name = String((args && args.name) || '').trim(); if (!name) return { error: true, text: 'Name fehlt.' }; const payload = buildItemPayload(args); let created; try { const raw = runBw(['create', 'item'], b64(JSON.stringify(payload))); created = JSON.parse(raw); } catch (e) { return { error: true, text: `Anlegen fehlgeschlagen: ${String(e.stderr || e.message || e)}` }; } return { error: false, text: `## Angelegt: ${created.name || name}\n\n- ID: ${created.id}\n- Typ: ${typeName(created.type)}\n- Benutzer: ${(created.login || {}).username || '-'}\n- Ordner: ${created.folderId || '(kein)'}`, }; } async function updateItem(args) { const u = ensureSession(); if (u.error) return { error: true, text: u.error }; const id = String((args && args.id) || '').trim(); if (!id) return { error: true, text: 'Eintrags-ID fehlt.' }; let cur; try { cur = JSON.parse(runBw(['get', 'item', id])); } catch (e) { return { error: true, text: `Eintrag ${id} nicht lesbar: ${String(e.stderr || e.message || e)}` }; } if (!cur || cur.error) return { error: true, text: `Eintrag ${id} nicht gefunden.` }; if (args.name !== undefined) cur.name = String(args.name); if (args.notes !== undefined) cur.notes = args.notes || null; if (args.favorite !== undefined) cur.favorite = Boolean(args.favorite); if (args.folder_id !== undefined) cur.folderId = args.folder_id ? String(args.folder_id) : null; const login = cur.login || {}; if (args.username !== undefined) login.username = String(args.username); if (args.password !== undefined) login.password = String(args.password); if (args.uris !== undefined) login.uris = args.uris.length ? args.uris.map((u) => ({ uri: u })) : []; if (cur.type === 1 && Object.keys(login).length) cur.login = login; let updated; try { const raw = runBw(['edit', 'item', id], b64(JSON.stringify(cur))); updated = JSON.parse(raw); } catch (e) { return { error: true, text: `Aendern fehlgeschlagen: ${String(e.stderr || e.message || e)}` }; } return { error: false, text: `## Geaendert: ${updated.name || cur.name}\n\n- ID: ${updated.id}\n- Benutzer: ${(updated.login || {}).username || '-'}\n- Revision: ${relTime(updated.revisionDate)}`, }; } async function deleteItem(args) { const u = ensureSession(); if (u.error) return { error: true, text: u.error }; const id = String((args && args.id) || '').trim(); if (!id) return { error: true, text: 'Eintrags-ID fehlt.' }; let name = '-'; try { const raw = runBw(['get', 'item', id]); const got = JSON.parse(raw); if (got && got.name) name = got.name; } catch (e) { /* id existiert evtl. nicht */ } try { runBw(['delete', 'item', id]); } catch (e) { return { error: true, text: `Loeschen fehlgeschlagen: ${String(e.stderr || e.message || e)}` }; } return { error: false, text: `## Geloescht: ${name}\n\n- ID: ${id}` }; } async function generate(args) { const u = ensureSession(); if (u.error) return { error: true, text: u.error }; const args2 = []; if (args && args.passphrase) { args2.push('--passphrase'); args2.push('--words', String(Math.min(64, Math.max(3, Number((args && args.length) || 5))))); } else { const len = Math.min(128, Math.max(5, Number((args && args.length) || 24))); args2.push('--length', String(len)); if ((args && args.upper) !== false) args2.push('--uppercase'); if ((args && args.lower) !== false) args2.push('--lowercase'); if ((args && args.number) !== false) args2.push('--number'); if ((args && args.special) !== false) args2.push('--special'); if (args && args.ambiguous) args2.push('--ambiguous'); } let pw; try { pw = runBw(['generate', ...args2]).trim(); } catch (e) { return { error: true, text: `Erzeugen fehlgeschlagen: ${String(e.stderr || e.message || e)}` }; } if (!pw) return { error: true, text: 'bw generate gab nichts zurueck.' }; return { error: false, text: `## Generiertes Passwort\n\n\`${pw}\`` }; } function reply(id, result) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); } function replyError(id, code, message) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\n'); } let buf = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', (chunk) => { buf += chunk; let idx; while ((idx = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, idx).trim(); buf = buf.slice(idx + 1); if (!line) continue; handle(line); } }); function handle(line) { let msg; try { msg = JSON.parse(line); } catch (e) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) + '\n'); return; } const { id, method, params } = msg; if (method === 'notifications/initialized' || (id === undefined && method)) return; if (method === 'initialize') { reply(id, { protocolVersion: (params && params.protocolVersion) || '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'bitwarden', version: '1.2.0' }, }); return; } if (method === 'ping') { reply(id, {}); return; } if (method === 'tools/list') { reply(id, { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema, annotations: { title: name.replace(/_/g, ' '), readOnlyHint: /^bw_(status|list_items|search|get_item|generate)$/.test(name), destructiveHint: name === 'bw_delete_item', idempotentHint: !/delete/.test(name), openWorldHint: true, }, })), }); return; } if (method === 'tools/call') { const name = params && params.name; const args = (params && params.arguments) || {}; const dispatch = { bw_status: () => bwStatus(), bw_list_items: () => listItems(args), bw_search: () => searchItems(args), bw_get_item: () => getItem(args), bw_create_item: () => createItem(args), bw_update_item: () => updateItem(args), bw_delete_item: () => deleteItem(args), bw_generate: () => generate(args), }; const fn = dispatch[name]; if (!fn) { reply(id, { content: [{ type: 'text', text: `Unbekanntes oder nicht freigegebenes Werkzeug: ${name}` }], isError: true }); return; } fn() .then((r) => reply(id, { content: [{ type: 'text', text: r.text }], isError: Boolean(r.error) })) .catch((e) => reply(id, { content: [{ type: 'text', text: `Interner Fehler: ${e.message || e}` }], isError: true })); return; } replyError(id, -32601, 'Method not found'); }