@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.
- package/bin/patch-bitwarden-cli-lib.js +159 -33
- package/bin/patch-bitwarden-cli-policy.js +62 -0
- package/dist/bw/bwCli.js +29 -40
- package/dist/bw/bwCommandDisplay.js +133 -0
- package/dist/bw/bwEnv.js +34 -0
- package/dist/bw/bwSession.js +25 -434
- package/dist/bw/bwSessionAuth.js +201 -0
- package/dist/bw/bwSessionStorage.js +191 -0
- package/package.json +5 -5
package/dist/bw/bwSession.js
CHANGED
|
@@ -1,137 +1,34 @@
|
|
|
1
|
-
// src/bw/bwSession.ts
|
|
2
|
-
import { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
1
|
import { isBwAuthSessionInvalidError, runBw } from './bwCli.js';
|
|
2
|
+
import { BwSessionAuth } from './bwSessionAuth.js';
|
|
5
3
|
import { Mutex } from './mutex.js';
|
|
6
|
-
|
|
7
|
-
const POST_LOGIN_UNLOCK_RETRY_DELAY_MS = 2_000;
|
|
8
|
-
const PROCESS_LOCK_WAIT_MS = 100;
|
|
9
|
-
const PROCESS_LOCK_TIMEOUT_MS = 90_000;
|
|
10
|
-
const PROCESS_LOCK_OWNER_FILE = 'owner.json';
|
|
11
|
-
function sleep(ms) {
|
|
12
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
13
|
-
}
|
|
14
|
-
function isProcessLockOwner(value) {
|
|
15
|
-
return (typeof value === 'object' &&
|
|
16
|
-
value !== null &&
|
|
17
|
-
'pid' in value &&
|
|
18
|
-
'createdAt' in value &&
|
|
19
|
-
typeof value.pid === 'number' &&
|
|
20
|
-
Number.isInteger(value.pid) &&
|
|
21
|
-
typeof value.createdAt === 'string');
|
|
22
|
-
}
|
|
23
|
-
function isProcessAlive(pid) {
|
|
24
|
-
if (pid <= 0)
|
|
25
|
-
return false;
|
|
26
|
-
try {
|
|
27
|
-
process.kill(pid, 0);
|
|
28
|
-
return true;
|
|
29
|
-
}
|
|
30
|
-
catch (error) {
|
|
31
|
-
if (!(error instanceof Error))
|
|
32
|
-
throw error;
|
|
33
|
-
return errorCode(error) !== 'ESRCH';
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
function errorCode(error) {
|
|
37
|
-
if (typeof error !== 'object' || error === null || !('code' in error)) {
|
|
38
|
-
return undefined;
|
|
39
|
-
}
|
|
40
|
-
return error.code;
|
|
41
|
-
}
|
|
42
|
-
function requiredEnv(name) {
|
|
43
|
-
const v = process.env[name];
|
|
44
|
-
if (!v) {
|
|
45
|
-
throw new Error(`Missing required env var for stdio mode: ${name}. ` +
|
|
46
|
-
'For --stdio, set BW_HOST, BW_PASSWORD, and either ' +
|
|
47
|
-
'BW_CLIENTID+BW_CLIENTSECRET or BW_USER/BW_USERNAME. ' +
|
|
48
|
-
'For HTTP mode, omit --stdio and send X-BW-* headers per request.');
|
|
49
|
-
}
|
|
50
|
-
return v;
|
|
51
|
-
}
|
|
52
|
-
export function readBwEnv() {
|
|
53
|
-
const unlockIntervalSecondsRaw = process.env.BW_UNLOCK_INTERVAL ?? '300';
|
|
54
|
-
const unlockIntervalSeconds = Number.parseInt(unlockIntervalSecondsRaw, 10);
|
|
55
|
-
const host = requiredEnv('BW_HOST');
|
|
56
|
-
const password = requiredEnv('BW_PASSWORD');
|
|
57
|
-
const clientId = process.env.BW_CLIENTID;
|
|
58
|
-
const clientSecret = process.env.BW_CLIENTSECRET;
|
|
59
|
-
const user = process.env.BW_USER ?? process.env.BW_USERNAME;
|
|
60
|
-
const login = clientId && clientSecret
|
|
61
|
-
? { method: 'apikey', clientId, clientSecret }
|
|
62
|
-
: user
|
|
63
|
-
? { method: 'userpass', user }
|
|
64
|
-
: (() => {
|
|
65
|
-
throw new Error('Missing login env: set BW_CLIENTID+BW_CLIENTSECRET or BW_USER/BW_USERNAME');
|
|
66
|
-
})();
|
|
67
|
-
return {
|
|
68
|
-
host,
|
|
69
|
-
password,
|
|
70
|
-
unlockIntervalSeconds: Number.isFinite(unlockIntervalSeconds)
|
|
71
|
-
? unlockIntervalSeconds
|
|
72
|
-
: 300,
|
|
73
|
-
login,
|
|
74
|
-
};
|
|
75
|
-
}
|
|
4
|
+
export { readBwEnv } from './bwEnv.js';
|
|
76
5
|
export class BwSessionManager {
|
|
77
6
|
env;
|
|
78
7
|
lock = new Mutex();
|
|
79
|
-
|
|
8
|
+
auth;
|
|
80
9
|
templateItem = null;
|
|
81
10
|
keepaliveTimer = null;
|
|
82
11
|
warmupPromise = null;
|
|
83
|
-
configuredHost = null;
|
|
84
|
-
homeDir;
|
|
85
|
-
appDataDir;
|
|
86
|
-
processLockDir;
|
|
87
|
-
sessionStatePath;
|
|
88
12
|
constructor(env) {
|
|
89
13
|
this.env = env;
|
|
90
|
-
this.
|
|
91
|
-
|
|
92
|
-
this.processLockDir = join(this.appDataDir, '.warden-mcp-auth-lock');
|
|
93
|
-
this.sessionStatePath = join(this.appDataDir, '.warden-mcp-session.json');
|
|
94
|
-
}
|
|
95
|
-
baseEnv(extra) {
|
|
96
|
-
return {
|
|
97
|
-
HOME: this.homeDir,
|
|
98
|
-
BITWARDENCLI_APPDATA_DIR: this.appDataDir,
|
|
99
|
-
...(extra ?? {}),
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
// Must be called while holding `this.lock` (i.e. from within `withSession`).
|
|
103
|
-
async getTemplateItemLocked(session) {
|
|
104
|
-
if (this.templateItem)
|
|
105
|
-
return this.templateItem;
|
|
106
|
-
const { stdout } = await runBw(['--session', session, 'get', 'template', 'item'], {
|
|
107
|
-
env: this.baseEnv(),
|
|
108
|
-
timeoutMs: 60_000,
|
|
14
|
+
this.auth = new BwSessionAuth(env, () => {
|
|
15
|
+
this.templateItem = null;
|
|
109
16
|
});
|
|
110
|
-
let parsed;
|
|
111
|
-
try {
|
|
112
|
-
parsed = JSON.parse(stdout);
|
|
113
|
-
}
|
|
114
|
-
catch (err) {
|
|
115
|
-
throw new Error(`Failed to parse bw template output (${stdout.length} bytes)`, { cause: err });
|
|
116
|
-
}
|
|
117
|
-
this.templateItem = parsed;
|
|
118
|
-
return parsed;
|
|
119
17
|
}
|
|
120
18
|
startKeepUnlocked() {
|
|
121
19
|
if (this.keepaliveTimer)
|
|
122
20
|
return;
|
|
123
21
|
const intervalMs = Math.max(10, this.env.unlockIntervalSeconds) * 1000;
|
|
124
22
|
this.keepaliveTimer = setInterval(() => {
|
|
125
|
-
if (!this.
|
|
23
|
+
if (!this.auth.hasSession())
|
|
126
24
|
return;
|
|
127
25
|
void this.lock.runExclusive(async () => {
|
|
128
26
|
try {
|
|
129
|
-
await this.
|
|
27
|
+
await this.auth.ensureUnlocked();
|
|
130
28
|
}
|
|
131
29
|
catch (error) {
|
|
132
30
|
if (!(error instanceof Error))
|
|
133
31
|
throw error;
|
|
134
|
-
// Keepalive is best-effort; tools will surface failures.
|
|
135
32
|
}
|
|
136
33
|
});
|
|
137
34
|
}, intervalMs);
|
|
@@ -139,42 +36,38 @@ export class BwSessionManager {
|
|
|
139
36
|
}
|
|
140
37
|
async withSession(fn) {
|
|
141
38
|
return this.lock.runExclusive(async () => {
|
|
142
|
-
const session = await this.
|
|
39
|
+
const session = await this.auth.ensureUnlocked();
|
|
143
40
|
try {
|
|
144
41
|
return await fn(session);
|
|
145
42
|
}
|
|
146
43
|
catch (error) {
|
|
147
44
|
if (!isBwAuthSessionInvalidError(error))
|
|
148
45
|
throw error;
|
|
149
|
-
await this.
|
|
150
|
-
const refreshedSession = await this.ensureUnlockedInternal();
|
|
46
|
+
const refreshedSession = await this.auth.ensureUnlocked(session);
|
|
151
47
|
return fn(refreshedSession);
|
|
152
48
|
}
|
|
153
49
|
});
|
|
154
50
|
}
|
|
155
51
|
async getTemplateItem() {
|
|
156
52
|
return this.lock.runExclusive(async () => {
|
|
157
|
-
const session = await this.
|
|
53
|
+
const session = await this.auth.ensureUnlocked();
|
|
158
54
|
return this.getTemplateItemLocked(session);
|
|
159
55
|
});
|
|
160
56
|
}
|
|
161
|
-
// Use this inside a `withSession` callback to avoid deadlocking by re-taking the same mutex.
|
|
162
57
|
async getTemplateItemForSession(session) {
|
|
163
58
|
return this.getTemplateItemLocked(session);
|
|
164
59
|
}
|
|
165
60
|
async status() {
|
|
166
61
|
const { stdout } = await runBw(['status'], {
|
|
167
|
-
env: this.baseEnv(),
|
|
62
|
+
env: this.auth.storage.baseEnv(),
|
|
168
63
|
timeoutMs: 60_000,
|
|
169
64
|
});
|
|
170
65
|
let parsed;
|
|
171
66
|
try {
|
|
172
67
|
parsed = JSON.parse(stdout);
|
|
173
68
|
}
|
|
174
|
-
catch (
|
|
175
|
-
throw new Error(`Failed to parse bw status output (${stdout.length} bytes)`, {
|
|
176
|
-
cause: err,
|
|
177
|
-
});
|
|
69
|
+
catch (error) {
|
|
70
|
+
throw new Error(`Failed to parse bw status output (${stdout.length} bytes)`, { cause: error });
|
|
178
71
|
}
|
|
179
72
|
const rawStatus = typeof parsed.status === 'string' ? parsed.status : null;
|
|
180
73
|
const serverUrl = typeof parsed.serverUrl === 'string' ? parsed.serverUrl : this.env.host;
|
|
@@ -183,24 +76,10 @@ export class BwSessionManager {
|
|
|
183
76
|
: this.env.login.method === 'userpass'
|
|
184
77
|
? this.env.login.user
|
|
185
78
|
: null;
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
isUnlocked = true;
|
|
190
|
-
}
|
|
191
|
-
else {
|
|
192
|
-
const storedSession = await this.readStoredSessionState();
|
|
193
|
-
if (storedSession?.session &&
|
|
194
|
-
(await this.isSessionValid(storedSession.session))) {
|
|
195
|
-
this.session = storedSession.session;
|
|
196
|
-
await this.writeStoredSessionState(storedSession.session);
|
|
197
|
-
isUnlocked = true;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
if (rawStatus === 'locked') {
|
|
79
|
+
const isUnlocked = rawStatus === 'unlocked' ||
|
|
80
|
+
(await this.auth.hasValidSessionWithoutUnlock());
|
|
81
|
+
if (rawStatus === 'locked')
|
|
202
82
|
this.startBackgroundUnlock();
|
|
203
|
-
}
|
|
204
83
|
const summaryParts = isUnlocked
|
|
205
84
|
? ['Vault access ready']
|
|
206
85
|
: [
|
|
@@ -224,170 +103,26 @@ export class BwSessionManager {
|
|
|
224
103
|
},
|
|
225
104
|
};
|
|
226
105
|
}
|
|
227
|
-
// Run a bw command within an existing session, using this manager's HOME/profile.
|
|
228
|
-
// Intended to be used from inside `withSession` to avoid relocking.
|
|
229
106
|
async runForSession(session, args, opts = {}) {
|
|
230
107
|
return runBw(['--session', session, ...args], {
|
|
231
108
|
...opts,
|
|
232
|
-
env: this.baseEnv(opts.env),
|
|
109
|
+
env: this.auth.storage.baseEnv(opts.env),
|
|
233
110
|
});
|
|
234
111
|
}
|
|
235
|
-
async
|
|
236
|
-
this.
|
|
237
|
-
|
|
238
|
-
await this.
|
|
239
|
-
}
|
|
240
|
-
async resetCliProfile() {
|
|
241
|
-
await this.clearSessionStateLocked();
|
|
242
|
-
this.configuredHost = null;
|
|
243
|
-
await runBw(['logout'], { env: this.baseEnv(), timeoutMs: 30_000 }).catch(() => { });
|
|
244
|
-
const home = this.homeDir;
|
|
245
|
-
const cliStateDirs = [
|
|
246
|
-
this.appDataDir,
|
|
247
|
-
join(home, '.config', 'Bitwarden CLI'),
|
|
248
|
-
join(home, 'Library', 'Application Support', 'Bitwarden CLI'),
|
|
249
|
-
join(home, 'AppData', 'Roaming', 'Bitwarden CLI'),
|
|
250
|
-
];
|
|
251
|
-
for (const dir of cliStateDirs) {
|
|
252
|
-
await rm(join(dir, 'data.json'), {
|
|
253
|
-
force: true,
|
|
254
|
-
}).catch(() => { });
|
|
255
|
-
await rm(join(dir, 'config.json'), {
|
|
256
|
-
force: true,
|
|
257
|
-
}).catch(() => { });
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
async currentServerUrl() {
|
|
112
|
+
async getTemplateItemLocked(session) {
|
|
113
|
+
if (this.templateItem)
|
|
114
|
+
return this.templateItem;
|
|
115
|
+
const { stdout } = await runBw(['--session', session, 'get', 'template', 'item'], { env: this.auth.storage.baseEnv(), timeoutMs: 60_000 });
|
|
261
116
|
try {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
const parsed = JSON.parse(raw);
|
|
265
|
-
const base = parsed.global_environment_environment?.urls?.base;
|
|
266
|
-
if (typeof base === 'string' && base.length > 0) {
|
|
267
|
-
return base;
|
|
268
|
-
}
|
|
117
|
+
this.templateItem = JSON.parse(stdout);
|
|
118
|
+
return this.templateItem;
|
|
269
119
|
}
|
|
270
120
|
catch (error) {
|
|
271
|
-
|
|
272
|
-
throw error;
|
|
273
|
-
// Fall back to the CLI if local state is absent or unreadable.
|
|
274
|
-
}
|
|
275
|
-
try {
|
|
276
|
-
const { stdout } = await runBw(['status'], {
|
|
277
|
-
env: this.baseEnv(),
|
|
278
|
-
timeoutMs: 30_000,
|
|
279
|
-
});
|
|
280
|
-
const parsed = JSON.parse(stdout);
|
|
281
|
-
return typeof parsed.serverUrl === 'string' ? parsed.serverUrl : null;
|
|
282
|
-
}
|
|
283
|
-
catch {
|
|
284
|
-
return null;
|
|
121
|
+
throw new Error(`Failed to parse bw template output (${stdout.length} bytes)`, { cause: error });
|
|
285
122
|
}
|
|
286
123
|
}
|
|
287
|
-
async ensureUnlockedInternal() {
|
|
288
|
-
return this.withProcessAuthLock(async () => {
|
|
289
|
-
// Ensure server config points to BW_HOST.
|
|
290
|
-
await this.ensureServerConfigured();
|
|
291
|
-
// If we already have a session, check if it still works.
|
|
292
|
-
if (this.session) {
|
|
293
|
-
if (await this.isSessionValid(this.session)) {
|
|
294
|
-
return this.session;
|
|
295
|
-
}
|
|
296
|
-
this.session = null;
|
|
297
|
-
}
|
|
298
|
-
const storedSession = await this.readStoredSessionState();
|
|
299
|
-
if (storedSession?.session) {
|
|
300
|
-
if (await this.isSessionValid(storedSession.session)) {
|
|
301
|
-
this.session = storedSession.session;
|
|
302
|
-
await this.writeStoredSessionState(storedSession.session);
|
|
303
|
-
return storedSession.session;
|
|
304
|
-
}
|
|
305
|
-
await this.clearStoredSessionState();
|
|
306
|
-
}
|
|
307
|
-
const unlockEnv = this.baseEnv({
|
|
308
|
-
BW_PASSWORD: this.env.password,
|
|
309
|
-
BW_HOST: this.env.host,
|
|
310
|
-
});
|
|
311
|
-
const tryUnlock = async () => {
|
|
312
|
-
try {
|
|
313
|
-
const { stdout } = await runBw(['unlock', '--passwordenv', 'BW_PASSWORD', '--raw'], { env: unlockEnv, timeoutMs: 60_000, noInteraction: false });
|
|
314
|
-
return stdout.trim();
|
|
315
|
-
}
|
|
316
|
-
catch {
|
|
317
|
-
return '';
|
|
318
|
-
}
|
|
319
|
-
};
|
|
320
|
-
const tryLoginRaw = async () => {
|
|
321
|
-
try {
|
|
322
|
-
if (this.env.login.method === 'apikey') {
|
|
323
|
-
const { stdout } = await runBw(['login', '--apikey', '--raw'], {
|
|
324
|
-
env: this.baseEnv({
|
|
325
|
-
BW_CLIENTID: this.env.login.clientId,
|
|
326
|
-
BW_CLIENTSECRET: this.env.login.clientSecret,
|
|
327
|
-
BW_HOST: this.env.host,
|
|
328
|
-
}),
|
|
329
|
-
timeoutMs: 60_000,
|
|
330
|
-
noInteraction: false,
|
|
331
|
-
});
|
|
332
|
-
return { completed: true, session: stdout.trim() };
|
|
333
|
-
}
|
|
334
|
-
const { stdout } = await runBw([
|
|
335
|
-
'login',
|
|
336
|
-
this.env.login.user,
|
|
337
|
-
'--passwordenv',
|
|
338
|
-
'BW_PASSWORD',
|
|
339
|
-
'--raw',
|
|
340
|
-
], { env: unlockEnv, timeoutMs: 60_000, noInteraction: false });
|
|
341
|
-
const session = stdout.trim();
|
|
342
|
-
if (!session)
|
|
343
|
-
return { completed: false, session: '' };
|
|
344
|
-
return { completed: true, session };
|
|
345
|
-
}
|
|
346
|
-
catch {
|
|
347
|
-
return { completed: false, session: '' };
|
|
348
|
-
}
|
|
349
|
-
};
|
|
350
|
-
const retryUnlockAfterLogin = async () => {
|
|
351
|
-
for (let attempt = 0; attempt < POST_LOGIN_UNLOCK_RETRY_ATTEMPTS; attempt += 1) {
|
|
352
|
-
const session = await tryUnlock();
|
|
353
|
-
if (session)
|
|
354
|
-
return session;
|
|
355
|
-
if (attempt < POST_LOGIN_UNLOCK_RETRY_ATTEMPTS - 1) {
|
|
356
|
-
await sleep(POST_LOGIN_UNLOCK_RETRY_DELAY_MS);
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
return '';
|
|
360
|
-
};
|
|
361
|
-
const obtainSession = async () => {
|
|
362
|
-
let session = await tryUnlock();
|
|
363
|
-
if (!session) {
|
|
364
|
-
const login = await tryLoginRaw();
|
|
365
|
-
if (login.session) {
|
|
366
|
-
session = login.session;
|
|
367
|
-
}
|
|
368
|
-
else if (login.completed) {
|
|
369
|
-
session = await retryUnlockAfterLogin();
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
if (!session)
|
|
373
|
-
session = await tryUnlock();
|
|
374
|
-
return session;
|
|
375
|
-
};
|
|
376
|
-
let session = await obtainSession();
|
|
377
|
-
if (!session) {
|
|
378
|
-
await this.resetCliProfile();
|
|
379
|
-
await this.ensureServerConfigured();
|
|
380
|
-
session = await obtainSession();
|
|
381
|
-
}
|
|
382
|
-
if (!session)
|
|
383
|
-
throw new Error('bw login/unlock returned an empty session');
|
|
384
|
-
this.session = session;
|
|
385
|
-
await this.writeStoredSessionState(session);
|
|
386
|
-
return session;
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
124
|
startBackgroundUnlock() {
|
|
390
|
-
if (this.
|
|
125
|
+
if (this.auth.hasSession() || this.warmupPromise)
|
|
391
126
|
return;
|
|
392
127
|
this.warmupPromise = this.withSession(async () => undefined)
|
|
393
128
|
.catch(() => { })
|
|
@@ -395,148 +130,4 @@ export class BwSessionManager {
|
|
|
395
130
|
this.warmupPromise = null;
|
|
396
131
|
});
|
|
397
132
|
}
|
|
398
|
-
sessionIdentity() {
|
|
399
|
-
return this.env.login.method === 'apikey'
|
|
400
|
-
? `apikey:${this.env.login.clientId}`
|
|
401
|
-
: `userpass:${this.env.login.user}`;
|
|
402
|
-
}
|
|
403
|
-
async isSessionValid(session) {
|
|
404
|
-
try {
|
|
405
|
-
const { stdout } = await runBw(['--session', session, 'unlock', '--check'], {
|
|
406
|
-
env: this.baseEnv(),
|
|
407
|
-
timeoutMs: 30_000,
|
|
408
|
-
});
|
|
409
|
-
void stdout;
|
|
410
|
-
return true;
|
|
411
|
-
}
|
|
412
|
-
catch {
|
|
413
|
-
return false;
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
async readStoredSessionState() {
|
|
417
|
-
try {
|
|
418
|
-
const raw = await readFile(this.sessionStatePath, 'utf8');
|
|
419
|
-
const parsed = JSON.parse(raw);
|
|
420
|
-
if (parsed.version !== 1 ||
|
|
421
|
-
parsed.host !== this.env.host ||
|
|
422
|
-
parsed.identity !== this.sessionIdentity() ||
|
|
423
|
-
typeof parsed.session !== 'string' ||
|
|
424
|
-
parsed.session.length === 0) {
|
|
425
|
-
return null;
|
|
426
|
-
}
|
|
427
|
-
return parsed;
|
|
428
|
-
}
|
|
429
|
-
catch {
|
|
430
|
-
return null;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
async writeStoredSessionState(session) {
|
|
434
|
-
const now = new Date().toISOString();
|
|
435
|
-
const state = {
|
|
436
|
-
version: 1,
|
|
437
|
-
host: this.env.host,
|
|
438
|
-
identity: this.sessionIdentity(),
|
|
439
|
-
session,
|
|
440
|
-
createdAt: now,
|
|
441
|
-
validatedAt: now,
|
|
442
|
-
};
|
|
443
|
-
await mkdir(this.appDataDir, { recursive: true });
|
|
444
|
-
await writeFile(this.sessionStatePath, JSON.stringify(state), 'utf8');
|
|
445
|
-
}
|
|
446
|
-
async clearStoredSessionState() {
|
|
447
|
-
await rm(this.sessionStatePath, { force: true }).catch(() => { });
|
|
448
|
-
}
|
|
449
|
-
async withProcessAuthLock(fn) {
|
|
450
|
-
const startedAt = Date.now();
|
|
451
|
-
await mkdir(this.appDataDir, { recursive: true });
|
|
452
|
-
while (true) {
|
|
453
|
-
try {
|
|
454
|
-
await mkdir(this.processLockDir);
|
|
455
|
-
try {
|
|
456
|
-
await this.writeProcessLockOwner();
|
|
457
|
-
}
|
|
458
|
-
catch (error) {
|
|
459
|
-
await rm(this.processLockDir, { recursive: true, force: true });
|
|
460
|
-
throw error;
|
|
461
|
-
}
|
|
462
|
-
break;
|
|
463
|
-
}
|
|
464
|
-
catch (error) {
|
|
465
|
-
if (errorCode(error) !== 'EEXIST')
|
|
466
|
-
throw error;
|
|
467
|
-
if (await this.reclaimProcessAuthLockIfStale())
|
|
468
|
-
continue;
|
|
469
|
-
if (Date.now() - startedAt >= PROCESS_LOCK_TIMEOUT_MS) {
|
|
470
|
-
throw new Error(`Timed out waiting for process auth lock after ${PROCESS_LOCK_TIMEOUT_MS}ms`);
|
|
471
|
-
}
|
|
472
|
-
await sleep(PROCESS_LOCK_WAIT_MS);
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
try {
|
|
476
|
-
return await fn();
|
|
477
|
-
}
|
|
478
|
-
finally {
|
|
479
|
-
await rm(this.processLockDir, { recursive: true, force: true }).catch(() => { });
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
async writeProcessLockOwner() {
|
|
483
|
-
const owner = {
|
|
484
|
-
pid: process.pid,
|
|
485
|
-
createdAt: new Date().toISOString(),
|
|
486
|
-
};
|
|
487
|
-
await writeFile(join(this.processLockDir, PROCESS_LOCK_OWNER_FILE), JSON.stringify(owner), 'utf8');
|
|
488
|
-
}
|
|
489
|
-
async reclaimProcessAuthLockIfStale() {
|
|
490
|
-
const ownerPath = join(this.processLockDir, PROCESS_LOCK_OWNER_FILE);
|
|
491
|
-
try {
|
|
492
|
-
const parsed = JSON.parse(await readFile(ownerPath, 'utf8'));
|
|
493
|
-
if (isProcessLockOwner(parsed) && !isProcessAlive(parsed.pid)) {
|
|
494
|
-
await rm(this.processLockDir, { recursive: true, force: true });
|
|
495
|
-
return true;
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
catch (error) {
|
|
499
|
-
if (!(error instanceof SyntaxError)) {
|
|
500
|
-
if (errorCode(error) !== 'ENOENT')
|
|
501
|
-
throw error;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
const lockStats = await stat(this.processLockDir).catch(() => null);
|
|
505
|
-
if (lockStats &&
|
|
506
|
-
Date.now() - lockStats.mtimeMs >= PROCESS_LOCK_TIMEOUT_MS) {
|
|
507
|
-
await rm(this.processLockDir, { recursive: true, force: true });
|
|
508
|
-
return true;
|
|
509
|
-
}
|
|
510
|
-
return false;
|
|
511
|
-
}
|
|
512
|
-
async ensureServerConfigured() {
|
|
513
|
-
if (this.configuredHost === this.env.host)
|
|
514
|
-
return;
|
|
515
|
-
const currentHost = await this.currentServerUrl();
|
|
516
|
-
if (currentHost === this.env.host) {
|
|
517
|
-
this.configuredHost = currentHost;
|
|
518
|
-
return;
|
|
519
|
-
}
|
|
520
|
-
// bw requires logout before config server update.
|
|
521
|
-
await runBw(['logout'], { env: this.baseEnv(), timeoutMs: 30_000 }).catch(() => { });
|
|
522
|
-
try {
|
|
523
|
-
await runBw(['config', 'server', this.env.host], {
|
|
524
|
-
env: this.baseEnv(),
|
|
525
|
-
timeoutMs: 30_000,
|
|
526
|
-
});
|
|
527
|
-
this.configuredHost = this.env.host;
|
|
528
|
-
return;
|
|
529
|
-
}
|
|
530
|
-
catch (error) {
|
|
531
|
-
if (!(error instanceof Error))
|
|
532
|
-
throw error;
|
|
533
|
-
// If the CLI data is corrupt/out-of-sync, wiping config is the fastest recovery.
|
|
534
|
-
}
|
|
535
|
-
await this.resetCliProfile();
|
|
536
|
-
await runBw(['config', 'server', this.env.host], {
|
|
537
|
-
env: this.baseEnv(),
|
|
538
|
-
timeoutMs: 30_000,
|
|
539
|
-
});
|
|
540
|
-
this.configuredHost = this.env.host;
|
|
541
|
-
}
|
|
542
133
|
}
|