@icoretech/warden-mcp 0.2.34 → 0.2.36

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.
@@ -1,10 +1,18 @@
1
- import { readFileSync, writeFileSync } from 'node:fs';
1
+ import {
2
+ chmodSync,
3
+ readFileSync,
4
+ renameSync,
5
+ rmSync,
6
+ statSync,
7
+ writeFileSync,
8
+ } from 'node:fs';
2
9
  import { createRequire } from 'node:module';
3
10
  import { dirname, join } from 'node:path';
4
11
  import { fileURLToPath } from 'node:url';
12
+ import { patchPolicyRevisionDate } from './patch-bitwarden-cli-policy.js';
5
13
 
6
14
  const require = createRequire(import.meta.url);
7
- const compatMarker = 'icoretech-vaultwarden-compat';
15
+ const loginCompatMarker = 'icoretech-vaultwarden-compat';
8
16
 
9
17
  function isModuleNotFoundFor(specifier, error) {
10
18
  if (!(error instanceof Error)) return false;
@@ -12,6 +20,19 @@ function isModuleNotFoundFor(specifier, error) {
12
20
  return error.message.includes(specifier);
13
21
  }
14
22
 
23
+ function atomicWriteFile(path, contents) {
24
+ const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;
25
+ try {
26
+ const mode = statSync(path).mode & 0o777;
27
+ writeFileSync(tempPath, contents, { encoding: 'utf8', flag: 'wx', mode });
28
+ chmodSync(tempPath, mode);
29
+ renameSync(tempPath, path);
30
+ } catch (error) {
31
+ rmSync(tempPath, { force: true });
32
+ throw error;
33
+ }
34
+ }
35
+
15
36
  export function resolveBundledBwCliPath({
16
37
  resolveDependency = (specifier) => require.resolve(specifier),
17
38
  } = {}) {
@@ -28,7 +49,7 @@ export function resolveBundledBwCliPath({
28
49
 
29
50
  function buildCompatBlock(indent) {
30
51
  return [
31
- `${indent}/* ${compatMarker} */`,
52
+ `${indent}/* ${loginCompatMarker} */`,
32
53
  `${indent}if (response.accountKeysResponseModel) {`,
33
54
  `${indent} yield this.accountCryptographicStateService.setAccountCryptographicState(response.accountKeysResponseModel.toWrappedAccountCryptographicState(), userId);`,
34
55
  `${indent}}`,
@@ -42,56 +63,161 @@ function buildCompatBlock(indent) {
42
63
  ].join('\n');
43
64
  }
44
65
 
45
- const strategyMethodRegex =
46
- /(setAccountCryptographicState\(response, userId\) \{\n\s+return [^\n]+\(\s*this, void 0, void 0, function\* \(\) \{\n)(\s*)yield this\.accountCryptographicStateService\.setAccountCryptographicState\(response\.accountKeysResponseModel\.toWrappedAccountCryptographicState\(\), userId\);\n(\s*\}\);\n\s*\})/g;
66
+ function hasValidLoginCompat(source) {
67
+ return source.includes(`/* ${loginCompatMarker} */`);
68
+ }
69
+
70
+ function countOccurrences(source, needle) {
71
+ let count = 0;
72
+ let index = source.indexOf(needle);
73
+ while (index !== -1) {
74
+ count += 1;
75
+ index = source.indexOf(needle, index + needle.length);
76
+ }
77
+ return count;
78
+ }
79
+
80
+ function findExactLineSequences(source, expectedLines) {
81
+ const lines = source.split('\n');
82
+ const starts = [];
83
+ for (let index = 0; index <= lines.length - expectedLines.length; index++) {
84
+ if (
85
+ expectedLines.every(
86
+ (expectedLine, offset) => lines[index + offset] === expectedLine,
87
+ )
88
+ ) {
89
+ starts.push(index);
90
+ }
91
+ }
92
+ return { lines, starts };
93
+ }
47
94
 
48
- const guardedStateRegex =
49
- /(^[ \t]*)if \(response\.accountKeysResponseModel\) \{\n[ \t]+yield this\.accountCryptographicStateService\.setAccountCryptographicState\(response\.accountKeysResponseModel\.toWrappedAccountCryptographicState\(\), userId\);\n\1\}/gm;
95
+ function replaceExactLineSequence(source, expectedLines, replacement) {
96
+ const { lines, starts } = findExactLineSequences(source, expectedLines);
97
+ if (starts.length !== 1) return null;
98
+ lines.splice(starts[0], expectedLines.length, ...replacement.split('\n'));
99
+ return lines.join('\n');
100
+ }
50
101
 
51
- export function patchBundledBwSource(source) {
102
+ function patchLoginCompat(source) {
103
+ const methodName = 'setAccountCryptographicState(response, userId) {';
104
+ let cursor = 0;
105
+ let searchFrom = 0;
106
+ let methods = 0;
52
107
  let replacements = 0;
108
+ let patchedSource = '';
53
109
 
54
- const guardedSource = source.replace(
55
- guardedStateRegex,
56
- (match, indent, offset, originalSource) => {
110
+ while (true) {
111
+ const methodStart = source.indexOf(methodName, searchFrom);
112
+ if (methodStart === -1) break;
113
+
114
+ const lineStart = source.lastIndexOf('\n', methodStart) + 1;
115
+ const indent = source.slice(lineStart, methodStart);
116
+ const methodCloseMarker = `\n${indent}}`;
117
+ const methodCloseStart = source.indexOf(methodCloseMarker, methodStart);
118
+ if (!/^[ \t]*$/.test(indent) || methodCloseStart === -1) {
119
+ return { source, replacements: 0, valid: false };
120
+ }
121
+
122
+ const methodEnd = methodCloseStart + methodCloseMarker.length;
123
+ const methodSource = source.slice(lineStart, methodEnd);
124
+ const generatorMarker = ', void 0, void 0, function* () {\n';
125
+ const bodyStart = methodSource.indexOf(generatorMarker);
126
+ const methodEndMarker = `\n${indent} });\n${indent}}`;
127
+ const bodyEnd = methodSource.length - methodEndMarker.length;
128
+ if (
129
+ !methodSource.endsWith(methodEndMarker) ||
130
+ bodyStart === -1 ||
131
+ bodyStart !== methodSource.lastIndexOf(generatorMarker) ||
132
+ bodyEnd < bodyStart
133
+ ) {
134
+ return { source, replacements: 0, valid: false };
135
+ }
136
+
137
+ const contentStart = bodyStart + generatorMarker.length;
138
+ const body = methodSource.slice(contentStart, bodyEnd);
139
+ const bodyIndent = `${indent} `;
140
+ const compatBlock = buildCompatBlock(bodyIndent);
141
+ const compatLines = compatBlock.split('\n');
142
+ const markerCount = countOccurrences(body, loginCompatMarker);
143
+ const accountKeysCall =
144
+ 'yield this.accountCryptographicStateService.setAccountCryptographicState(response.accountKeysResponseModel.toWrappedAccountCryptographicState(), userId);';
145
+ let patchedBody = body;
146
+
147
+ if (
148
+ markerCount === 1 &&
149
+ findExactLineSequences(body, compatLines).starts.length === 1
150
+ ) {
151
+ // Already patched.
152
+ } else if (markerCount === 0) {
153
+ const directState = `${bodyIndent}${accountKeysCall}`;
154
+ const guardedLines = [
155
+ `${bodyIndent}if (response.accountKeysResponseModel) {`,
156
+ `${bodyIndent} ${accountKeysCall}`,
157
+ `${bodyIndent}}`,
158
+ ];
159
+ const directLines = [directState];
160
+ const directCount = findExactLineSequences(body, directLines).starts
161
+ .length;
162
+ const guardedCount = findExactLineSequences(body, guardedLines).starts
163
+ .length;
164
+ const accountKeysCallCount = countOccurrences(body, accountKeysCall);
57
165
  if (
58
- originalSource
59
- .slice(0, offset)
60
- .endsWith(`${indent}/* ${compatMarker} */\n`)
166
+ accountKeysCallCount !== 1 ||
167
+ (guardedCount !== 1 && directCount !== 1)
61
168
  ) {
62
- return match;
169
+ return { source, replacements: 0, valid: false };
170
+ }
171
+ patchedBody = replaceExactLineSequence(
172
+ body,
173
+ guardedCount === 1 ? guardedLines : directLines,
174
+ compatBlock,
175
+ );
176
+ if (patchedBody === null) {
177
+ return { source, replacements: 0, valid: false };
63
178
  }
64
-
65
- replacements += 1;
66
- return buildCompatBlock(indent);
67
- },
68
- );
69
-
70
- const patchedSource = guardedSource.replace(
71
- strategyMethodRegex,
72
- (_match, prefix, indent, suffix) => {
73
179
  replacements += 1;
74
- return `${prefix}${buildCompatBlock(indent)}\n${suffix}`;
75
- },
76
- );
180
+ } else {
181
+ return { source, replacements: 0, valid: false };
182
+ }
77
183
 
78
- if (replacements > 0) {
79
- return { source: patchedSource, replacements };
184
+ methods += 1;
185
+ patchedSource += source.slice(cursor, lineStart);
186
+ patchedSource +=
187
+ methodSource.slice(0, contentStart) +
188
+ patchedBody +
189
+ methodSource.slice(bodyEnd);
190
+ cursor = methodEnd;
191
+ searchFrom = methodEnd;
80
192
  }
81
193
 
82
- if (source.includes(compatMarker)) {
83
- return { source, replacements: 0 };
194
+ patchedSource += source.slice(cursor);
195
+ const valid =
196
+ methods > 0 &&
197
+ countOccurrences(patchedSource, loginCompatMarker) === methods &&
198
+ hasValidLoginCompat(patchedSource);
199
+ return { source: patchedSource, replacements, valid };
200
+ }
201
+
202
+ export function patchBundledBwSource(source) {
203
+ const loginPatch = patchLoginCompat(source);
204
+ const policyPatch = patchPolicyRevisionDate(loginPatch.source);
205
+ const replacements = loginPatch.replacements + policyPatch.replacements;
206
+ const patchedSource = policyPatch.source;
207
+
208
+ if (loginPatch.valid && policyPatch.valid) {
209
+ return { source: patchedSource, replacements };
84
210
  }
85
211
 
86
212
  throw new Error(
87
- '[warden-mcp] could not locate the expected setAccountCryptographicState blocks in @bitwarden/cli/build/bw.js',
213
+ '[warden-mcp] could not locate every expected Vaultwarden compatibility block in @bitwarden/cli/build/bw.js',
88
214
  );
89
215
  }
90
216
 
91
217
  export function applyBundledBwPatch({
92
218
  resolveDependency,
93
219
  readFile = (path) => readFileSync(path, 'utf8'),
94
- writeFile = (path, contents) => writeFileSync(path, contents),
220
+ writeFile = atomicWriteFile,
95
221
  logError = (message) => console.error(message),
96
222
  } = {}) {
97
223
  let bwCliPath;
@@ -0,0 +1,62 @@
1
+ const policyRevisionDateCompatMarker =
2
+ 'icoretech-vaultwarden-policy-revision-date-compat';
3
+
4
+ export function patchPolicyRevisionDate(source) {
5
+ const className = 'class Policy extends Domain {';
6
+ const classStart = source.indexOf(className);
7
+ const classEnd = source.indexOf('\n}', classStart);
8
+ if (
9
+ classStart === -1 ||
10
+ classEnd === -1 ||
11
+ source.indexOf(className, classStart + className.length) !== -1
12
+ ) {
13
+ return { source, replacements: 0, valid: false };
14
+ }
15
+
16
+ const classSource = source.slice(classStart, classEnd + 2);
17
+ const staticMethodStart = classSource.indexOf('\n static fromResponse(');
18
+ if (staticMethodStart === -1) {
19
+ return { source, replacements: 0, valid: false };
20
+ }
21
+
22
+ const constructorSource = classSource.slice(0, staticMethodStart);
23
+ const unpatchedMatches = [
24
+ ...constructorSource.matchAll(
25
+ /(^[ \t]*)this\.revisionDate = new Date\(obj\.revisionDate\);$/gm,
26
+ ),
27
+ ];
28
+ const patchedMatches = [
29
+ ...constructorSource.matchAll(
30
+ /(^[ \t]*)\/\* icoretech-vaultwarden-policy-revision-date-compat \*\/\n\1this\.revisionDate = obj\.revisionDate == null\n\1 {4}\? undefined\n\1 {4}: new Date\(obj\.revisionDate\);$/gm,
31
+ ),
32
+ ];
33
+ if (unpatchedMatches.length === 0 && patchedMatches.length === 1) {
34
+ return { source, replacements: 0, valid: true };
35
+ }
36
+
37
+ const match = unpatchedMatches[0];
38
+ if (
39
+ unpatchedMatches.length !== 1 ||
40
+ patchedMatches.length !== 0 ||
41
+ typeof match?.index !== 'number'
42
+ ) {
43
+ return { source, replacements: 0, valid: false };
44
+ }
45
+
46
+ const indent = match[1] ?? '';
47
+ const assignmentStart = classStart + match.index;
48
+ const replacement = [
49
+ `${indent}/* ${policyRevisionDateCompatMarker} */\n`,
50
+ `${indent}this.revisionDate = obj.revisionDate == null\n`,
51
+ `${indent} ? undefined\n`,
52
+ `${indent} : new Date(obj.revisionDate);`,
53
+ ].join('');
54
+ return {
55
+ source:
56
+ source.slice(0, assignmentStart) +
57
+ replacement +
58
+ source.slice(assignmentStart + match[0].length),
59
+ replacements: 1,
60
+ valid: true,
61
+ };
62
+ }
package/dist/bw/bwCli.js CHANGED
@@ -1,26 +1,31 @@
1
1
  // src/bw/bwCli.ts
2
2
  import { spawn } from 'node:child_process';
3
+ import { renderSafeBwCommand } from './bwCommandDisplay.js';
3
4
  import { resolveBundledBwBin } from './resolveBwBin.js';
4
- const SENSITIVE_ARG_FLAGS = new Set([
5
- '--apikey',
6
- '--clientsecret',
7
- '--emails',
8
- '--password',
9
- '--passwordenv',
10
- '--passwordfile',
11
- '--session',
12
- ]);
13
5
  export class BwCliError extends Error {
14
6
  exitCode;
15
7
  stdout;
16
8
  stderr;
9
+ diagnosticCode;
17
10
  constructor(message, opts) {
18
11
  super(message);
19
12
  this.name = 'BwCliError';
20
13
  this.exitCode = opts.exitCode;
21
14
  this.stdout = opts.stdout;
22
15
  this.stderr = opts.stderr;
16
+ Object.defineProperties(this, {
17
+ stdout: { enumerable: false },
18
+ stderr: { enumerable: false },
19
+ });
20
+ this.diagnosticCode = opts.diagnosticCode ?? null;
21
+ }
22
+ }
23
+ function diagnoseBwCliFailure(stderr) {
24
+ if (stderr.includes('Error getting vault timeout: RangeError: Invalid time value') &&
25
+ stderr.includes('no elements in sequence')) {
26
+ return 'VAULTWARDEN_POLICY_REVISION_DATE';
23
27
  }
28
+ return null;
24
29
  }
25
30
  export function isBwAuthSessionInvalidError(error) {
26
31
  if (!(error instanceof BwCliError))
@@ -64,33 +69,8 @@ export async function runBw(args, opts = {}) {
64
69
  const env = { ...process.env, ...(opts.env ?? {}) };
65
70
  const debug = (process.env.KEYCHAIN_DEBUG_BW ?? 'false').toLowerCase() === 'true';
66
71
  const startedAt = Date.now();
67
- function safeArg(a) {
68
- if (typeof a !== 'string')
69
- return '<redacted>';
70
- // Avoid logging encoded JSON blobs (may contain secrets).
71
- if (a.length > 80)
72
- return '<redacted>';
73
- return a;
74
- }
75
- function safeRenderedArgs(argv) {
76
- const out = [];
77
- for (let i = 0; i < argv.length; i++) {
78
- const a = argv[i];
79
- if (typeof a === 'string' && SENSITIVE_ARG_FLAGS.has(a)) {
80
- out.push(a);
81
- if (i + 1 < argv.length) {
82
- out.push('<redacted>');
83
- i++;
84
- }
85
- continue;
86
- }
87
- out.push(safeArg(a));
88
- }
89
- return out.join(' ');
90
- }
91
72
  if (debug) {
92
- const rendered = safeRenderedArgs(finalArgs);
93
- console.log(`[bw] start: ${bwBin} ${rendered}`);
73
+ console.log(`[bw] start: ${renderSafeBwCommand(bwBin, finalArgs)}`);
94
74
  }
95
75
  const detached = process.platform !== 'win32';
96
76
  const child = spawn(bwBin, finalArgs, {
@@ -113,14 +93,18 @@ export async function runBw(args, opts = {}) {
113
93
  process.kill(-child.pid, 'SIGKILL');
114
94
  return;
115
95
  }
116
- catch {
96
+ catch (error) {
97
+ if (!(error instanceof Error))
98
+ throw error;
117
99
  // Fallback to direct child kill below.
118
100
  }
119
101
  }
120
102
  try {
121
103
  child.kill('SIGKILL');
122
104
  }
123
- catch {
105
+ catch (error) {
106
+ if (!(error instanceof Error))
107
+ throw error;
124
108
  // ignore
125
109
  }
126
110
  };
@@ -145,7 +129,7 @@ export async function runBw(args, opts = {}) {
145
129
  }, timeoutMs);
146
130
  child.on('error', (error) => {
147
131
  settle(() => {
148
- const safeCmd = `${bwBin} ${safeRenderedArgs(finalArgs)}`;
132
+ const safeCmd = renderSafeBwCommand(bwBin, finalArgs);
149
133
  if (error.code === 'ENOENT') {
150
134
  reject(new Error(`bw CLI not available for ${safeCmd}. Install @bitwarden/cli or set BW_BIN to a valid bw binary.`));
151
135
  return;
@@ -162,11 +146,16 @@ export async function runBw(args, opts = {}) {
162
146
  if (debug) {
163
147
  console.log(`[bw] fail: exit=${exitCode} ms=${Date.now() - startedAt}`);
164
148
  }
165
- const safeCmd = `${bwBin} ${safeRenderedArgs(finalArgs)}`;
166
- reject(new BwCliError(`${safeCmd} failed with exit code ${exitCode}`, {
149
+ const safeCmd = renderSafeBwCommand(bwBin, finalArgs);
150
+ const diagnosticCode = diagnoseBwCliFailure(stderr);
151
+ const diagnostic = diagnosticCode
152
+ ? ` [${diagnosticCode}: Vaultwarden policy data is missing revisionDate]`
153
+ : '';
154
+ reject(new BwCliError(`${safeCmd} failed with exit code ${exitCode}${diagnostic}`, {
167
155
  exitCode,
168
156
  stdout,
169
157
  stderr,
158
+ ...(diagnosticCode ? { diagnosticCode } : {}),
170
159
  }));
171
160
  return;
172
161
  }
@@ -0,0 +1,133 @@
1
+ import { basename } from 'node:path';
2
+ const COMMAND_PATHS = [
3
+ ['config', 'server'],
4
+ ['create', 'attachment'],
5
+ ['create', 'folder'],
6
+ ['create', 'item'],
7
+ ['create', 'org-collection'],
8
+ ['delete', 'attachment'],
9
+ ['delete', 'folder'],
10
+ ['delete', 'item'],
11
+ ['delete', 'org-collection'],
12
+ ['edit', 'folder'],
13
+ ['edit', 'item'],
14
+ ['edit', 'item-collections'],
15
+ ['edit', 'org-collection'],
16
+ ['encode'],
17
+ ['generate'],
18
+ ['get', 'attachment'],
19
+ ['get', 'collection'],
20
+ ['get', 'exposed'],
21
+ ['get', 'folder'],
22
+ ['get', 'item'],
23
+ ['get', 'notes'],
24
+ ['get', 'organization'],
25
+ ['get', 'org-collection'],
26
+ ['get', 'password'],
27
+ ['get', 'password-history'],
28
+ ['get', 'template', 'item'],
29
+ ['get', 'totp'],
30
+ ['get', 'uri'],
31
+ ['get', 'username'],
32
+ ['list', 'collections'],
33
+ ['list', 'folders'],
34
+ ['list', 'items'],
35
+ ['list', 'organizations'],
36
+ ['list', 'org-collections'],
37
+ ['lock'],
38
+ ['login'],
39
+ ['logout'],
40
+ ['move'],
41
+ ['receive'],
42
+ ['restore', 'item'],
43
+ ['send'],
44
+ ['status'],
45
+ ['sync'],
46
+ ['unlock'],
47
+ ];
48
+ const SAFE_OPTION_FLAGS = new Set([
49
+ '--apikey',
50
+ '--check',
51
+ '--cleanexit',
52
+ '--fullobject',
53
+ '--nointeraction',
54
+ '--obj',
55
+ '--raw',
56
+ '--response',
57
+ '--trash',
58
+ '--version',
59
+ ]);
60
+ const VALUE_OPTION_FLAGS = new Set([
61
+ '--clientsecret',
62
+ '--collectionid',
63
+ '--emails',
64
+ '--file',
65
+ '--folderid',
66
+ '--itemid',
67
+ '--organizationid',
68
+ '--password',
69
+ '--passwordenv',
70
+ '--passwordfile',
71
+ '--search',
72
+ '--session',
73
+ '--url',
74
+ ]);
75
+ export function renderSafeBwCommand(bwBin, argv) {
76
+ const rendered = [basename(bwBin)];
77
+ const commandPath = [];
78
+ let commandPathFrozen = false;
79
+ let redactRemaining = false;
80
+ for (let index = 0; index < argv.length; index += 1) {
81
+ const arg = argv[index];
82
+ if (redactRemaining) {
83
+ rendered.push('<redacted>');
84
+ continue;
85
+ }
86
+ if (typeof arg !== 'string') {
87
+ rendered.push('<redacted>');
88
+ if (commandPath.length > 0)
89
+ commandPathFrozen = true;
90
+ continue;
91
+ }
92
+ if (arg === '--') {
93
+ rendered.push(arg);
94
+ commandPathFrozen = true;
95
+ redactRemaining = true;
96
+ continue;
97
+ }
98
+ const equalsFlag = [...VALUE_OPTION_FLAGS].find((flag) => arg.startsWith(`${flag}=`));
99
+ if (equalsFlag) {
100
+ rendered.push(`${equalsFlag}=<redacted>`);
101
+ if (commandPath.length > 0)
102
+ commandPathFrozen = true;
103
+ continue;
104
+ }
105
+ if (VALUE_OPTION_FLAGS.has(arg)) {
106
+ rendered.push(arg);
107
+ if (index + 1 < argv.length) {
108
+ rendered.push('<redacted>');
109
+ index += 1;
110
+ }
111
+ if (commandPath.length > 0)
112
+ commandPathFrozen = true;
113
+ continue;
114
+ }
115
+ if (SAFE_OPTION_FLAGS.has(arg)) {
116
+ rendered.push(arg);
117
+ if (commandPath.length > 0)
118
+ commandPathFrozen = true;
119
+ continue;
120
+ }
121
+ const possibleCommandPaths = COMMAND_PATHS.filter((path) => commandPath.every((word, wordIndex) => path[wordIndex] === word));
122
+ if (!commandPathFrozen &&
123
+ possibleCommandPaths.some((path) => path[commandPath.length] === arg)) {
124
+ rendered.push(arg);
125
+ commandPath.push(arg);
126
+ continue;
127
+ }
128
+ rendered.push('<redacted>');
129
+ if (commandPath.length > 0)
130
+ commandPathFrozen = true;
131
+ }
132
+ return rendered.join(' ');
133
+ }
@@ -0,0 +1,34 @@
1
+ function requiredEnv(name) {
2
+ const value = process.env[name];
3
+ if (!value) {
4
+ throw new Error(`Missing required env var for stdio mode: ${name}. ` +
5
+ 'For --stdio, set BW_HOST, BW_PASSWORD, and either ' +
6
+ 'BW_CLIENTID+BW_CLIENTSECRET or BW_USER/BW_USERNAME. ' +
7
+ 'For HTTP mode, omit --stdio and send X-BW-* headers per request.');
8
+ }
9
+ return value;
10
+ }
11
+ export function readBwEnv() {
12
+ const rawInterval = process.env.BW_UNLOCK_INTERVAL ?? '300';
13
+ const unlockIntervalSeconds = Number.parseInt(rawInterval, 10);
14
+ const host = requiredEnv('BW_HOST');
15
+ const password = requiredEnv('BW_PASSWORD');
16
+ const clientId = process.env.BW_CLIENTID;
17
+ const clientSecret = process.env.BW_CLIENTSECRET;
18
+ const user = process.env.BW_USER ?? process.env.BW_USERNAME;
19
+ const login = clientId && clientSecret
20
+ ? { method: 'apikey', clientId, clientSecret }
21
+ : user
22
+ ? { method: 'userpass', user }
23
+ : (() => {
24
+ throw new Error('Missing login env: set BW_CLIENTID+BW_CLIENTSECRET or BW_USER/BW_USERNAME');
25
+ })();
26
+ return {
27
+ host,
28
+ password,
29
+ unlockIntervalSeconds: Number.isFinite(unlockIntervalSeconds)
30
+ ? unlockIntervalSeconds
31
+ : 300,
32
+ login,
33
+ };
34
+ }