@mcp-abap-adt/auth-providers 0.2.0 → 0.2.1
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/CHANGELOG.md +24 -0
- package/README.md +5 -3
- package/dist/auth/browserAuth.d.ts.map +1 -1
- package/dist/auth/browserAuth.js +123 -19
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.2.1] - 2025-01-XX
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- **Automatic Port Selection**: Browser auth server now automatically finds an available port if the requested port is in use
|
|
14
|
+
- When `startBrowserAuth()` is called with a port, it checks if the port is available
|
|
15
|
+
- If the port is busy, it automatically tries the next ports (up to 10 attempts)
|
|
16
|
+
- This prevents `EADDRINUSE` errors when multiple stdio servers run simultaneously
|
|
17
|
+
- Port selection happens before server startup, ensuring no conflicts
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
- **Server Port Cleanup**: Improved server shutdown to ensure ports are properly freed after authentication completes
|
|
21
|
+
- Added `keepAliveTimeout = 0` and `headersTimeout = 0` to prevent connections from staying open
|
|
22
|
+
- Added `closeAllConnections()` calls before `server.close()` to ensure all connections are closed
|
|
23
|
+
- Server now waits for HTTP response to finish before closing to prevent connection leaks
|
|
24
|
+
- Added proper error handling for browser open failures to ensure server is closed
|
|
25
|
+
- Server now properly closes in all error scenarios (timeout, browser open failure, callback errors)
|
|
26
|
+
- This prevents ports from remaining occupied after authentication completes or server shutdown
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
- **Port Selection Logic**: `startBrowserAuth()` now uses `findAvailablePort()` to automatically select a free port
|
|
30
|
+
- Default behavior: tries requested port first, then tries next ports if busy
|
|
31
|
+
- Port range: tries up to 10 consecutive ports starting from the requested port
|
|
32
|
+
- Logs when a different port is used (for debugging)
|
|
33
|
+
|
|
10
34
|
## [0.2.0] - 2025-12-19
|
|
11
35
|
|
|
12
36
|
### Added
|
package/README.md
CHANGED
|
@@ -173,10 +173,12 @@ import { BtpTokenProvider } from '@mcp-abap-adt/auth-providers';
|
|
|
173
173
|
import type { IAuthorizationConfig } from '@mcp-abap-adt/auth-broker';
|
|
174
174
|
|
|
175
175
|
// Create provider with default port (3001)
|
|
176
|
+
// The provider will automatically find an available port if 3001 is busy
|
|
176
177
|
const provider = new BtpTokenProvider();
|
|
177
178
|
|
|
178
|
-
// Or specify custom port for OAuth callback server
|
|
179
|
-
|
|
179
|
+
// Or specify custom port for OAuth callback server
|
|
180
|
+
// If the port is busy, the provider will automatically try the next ports
|
|
181
|
+
const providerWithCustomPort = new BtpTokenProvider(4002);
|
|
180
182
|
|
|
181
183
|
const authConfig: IAuthorizationConfig = {
|
|
182
184
|
uaaUrl: 'https://...authentication...hana.ondemand.com',
|
|
@@ -196,7 +198,7 @@ const result = await provider.getConnectionConfig(authConfig, {
|
|
|
196
198
|
// result.refreshToken contains refresh token (if browser flow was used)
|
|
197
199
|
```
|
|
198
200
|
|
|
199
|
-
**Note**: The `browserAuthPort` parameter (default: 3001) configures the OAuth callback server port. This is useful when running the provider in environments where
|
|
201
|
+
**Note**: The `browserAuthPort` parameter (default: 3001) configures the OAuth callback server port. The provider automatically finds an available port if the requested port is in use, preventing `EADDRINUSE` errors when multiple instances run simultaneously. The server properly closes all connections and frees the port after authentication completes, ensuring no lingering port occupation. This is useful when running the provider in environments where ports may be occupied (e.g., when running alongside a proxy server or multiple stdio servers).
|
|
200
202
|
|
|
201
203
|
### Token Validation
|
|
202
204
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browserAuth.d.ts","sourceRoot":"","sources":["../../src/auth/browserAuth.ts"],"names":[],"mappings":"AAAA;;GAEG;
|
|
1
|
+
{"version":3,"file":"browserAuth.d.ts","sourceRoot":"","sources":["../../src/auth/browserAuth.ts"],"names":[],"mappings":"AAAA;;GAEG;AAOH,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAyB9E;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,oBAAoB,EAChC,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,MAAa,EACnB,GAAG,CAAC,EAAE,OAAO,GAAG,IAAI,GACnB,OAAO,CAAC;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAsCzD;AAyCD;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CACpC,UAAU,EAAE,oBAAoB,EAChC,OAAO,GAAE,MAAiB,EAC1B,MAAM,CAAC,EAAE,OAAO,EAChB,IAAI,GAAE,MAAa,GAClB,OAAO,CAAC;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAwXzD"}
|
package/dist/auth/browserAuth.js
CHANGED
|
@@ -42,6 +42,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
42
42
|
exports.exchangeCodeForToken = exchangeCodeForToken;
|
|
43
43
|
exports.startBrowserAuth = startBrowserAuth;
|
|
44
44
|
const http = __importStar(require("http"));
|
|
45
|
+
const net = __importStar(require("net"));
|
|
45
46
|
const child_process = __importStar(require("child_process"));
|
|
46
47
|
const express_1 = __importDefault(require("express"));
|
|
47
48
|
const axios_1 = __importDefault(require("axios"));
|
|
@@ -111,6 +112,32 @@ function isDebugEnabled() {
|
|
|
111
112
|
process.env.DEBUG?.includes('auth-providers') === true ||
|
|
112
113
|
process.env.DEBUG?.includes('browser-auth') === true;
|
|
113
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Check if a port is available
|
|
117
|
+
*/
|
|
118
|
+
function isPortAvailable(port) {
|
|
119
|
+
return new Promise((resolve) => {
|
|
120
|
+
const server = net.createServer();
|
|
121
|
+
server.listen(port, () => {
|
|
122
|
+
server.once('close', () => resolve(true));
|
|
123
|
+
server.close();
|
|
124
|
+
});
|
|
125
|
+
server.on('error', () => resolve(false));
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Find an available port starting from the given port
|
|
130
|
+
* Tries ports in range [startPort, startPort + maxAttempts)
|
|
131
|
+
*/
|
|
132
|
+
async function findAvailablePort(startPort, maxAttempts = 10) {
|
|
133
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
134
|
+
const port = startPort + i;
|
|
135
|
+
if (await isPortAvailable(port)) {
|
|
136
|
+
return port;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
throw new Error(`No available port found in range ${startPort}-${startPort + maxAttempts - 1}`);
|
|
140
|
+
}
|
|
114
141
|
/**
|
|
115
142
|
* Start browser authentication flow
|
|
116
143
|
* @param authConfig Authorization configuration with UAA credentials
|
|
@@ -123,6 +150,17 @@ function isDebugEnabled() {
|
|
|
123
150
|
async function startBrowserAuth(authConfig, browser = 'system', logger, port = 3001) {
|
|
124
151
|
// Use logger if provided, otherwise null (no logging)
|
|
125
152
|
const log = logger || null;
|
|
153
|
+
// Find available port (try starting from requested port, then try next ports)
|
|
154
|
+
let actualPort;
|
|
155
|
+
try {
|
|
156
|
+
actualPort = await findAvailablePort(port, 10);
|
|
157
|
+
if (actualPort !== port) {
|
|
158
|
+
log?.debug(`Port ${port} is in use, using port ${actualPort} instead`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
throw new Error(`Failed to find available port starting from ${port}: ${error instanceof Error ? error.message : String(error)}`);
|
|
163
|
+
}
|
|
126
164
|
return new Promise((originalResolve, originalReject) => {
|
|
127
165
|
let timeoutId = null;
|
|
128
166
|
const resolve = (value) => {
|
|
@@ -137,7 +175,10 @@ async function startBrowserAuth(authConfig, browser = 'system', logger, port = 3
|
|
|
137
175
|
};
|
|
138
176
|
const app = (0, express_1.default)();
|
|
139
177
|
const server = http.createServer(app);
|
|
140
|
-
|
|
178
|
+
// Disable keep-alive to ensure connections close immediately
|
|
179
|
+
server.keepAliveTimeout = 0;
|
|
180
|
+
server.headersTimeout = 0;
|
|
181
|
+
const PORT = actualPort;
|
|
141
182
|
let serverInstance = null;
|
|
142
183
|
const authorizationUrl = getJwtAuthorizationUrl(authConfig, PORT);
|
|
143
184
|
// OAuth2 callback handler
|
|
@@ -284,36 +325,75 @@ async function startBrowserAuth(authConfig, browser = 'system', logger, port = 3
|
|
|
284
325
|
</div>
|
|
285
326
|
</body>
|
|
286
327
|
</html>`;
|
|
287
|
-
// Send success page first
|
|
328
|
+
// Send success page first and ensure response is finished
|
|
288
329
|
res.send(html);
|
|
330
|
+
// Wait for response to finish before closing server
|
|
331
|
+
res.on('finish', () => {
|
|
332
|
+
// Response finished, now we can safely close server
|
|
333
|
+
});
|
|
289
334
|
// Exchange code for tokens and close server
|
|
290
335
|
try {
|
|
291
336
|
const tokens = await exchangeCodeForToken(authConfig, code, PORT, log);
|
|
292
337
|
log?.info(`Tokens received: accessToken(${tokens.accessToken?.length || 0} chars), refreshToken(${tokens.refreshToken?.length || 0} chars)`);
|
|
293
|
-
// Close all connections
|
|
338
|
+
// Close all connections first to ensure port is freed
|
|
294
339
|
if (typeof server.closeAllConnections === 'function') {
|
|
295
340
|
server.closeAllConnections();
|
|
296
341
|
}
|
|
297
|
-
server
|
|
298
|
-
|
|
299
|
-
|
|
342
|
+
// Close server after response is finished
|
|
343
|
+
// This ensures the response connection is closed before server.close()
|
|
344
|
+
const closeServer = () => {
|
|
345
|
+
server.close(() => {
|
|
346
|
+
// Server closed - port should be freed
|
|
347
|
+
log?.debug(`Server closed, port ${PORT} should be freed`);
|
|
348
|
+
});
|
|
349
|
+
};
|
|
350
|
+
if (res.finished) {
|
|
351
|
+
// Response already finished, close immediately
|
|
352
|
+
closeServer();
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
// Wait for response to finish
|
|
356
|
+
res.once('finish', closeServer);
|
|
357
|
+
}
|
|
300
358
|
resolve(tokens);
|
|
301
359
|
}
|
|
302
360
|
catch (error) {
|
|
303
361
|
if (typeof server.closeAllConnections === 'function') {
|
|
304
362
|
server.closeAllConnections();
|
|
305
363
|
}
|
|
306
|
-
server.close(
|
|
307
|
-
|
|
308
|
-
|
|
364
|
+
// Use setTimeout to ensure connections are closed before server.close()
|
|
365
|
+
setTimeout(() => {
|
|
366
|
+
server.close(() => {
|
|
367
|
+
// Server closed on error - port should be freed
|
|
368
|
+
log?.debug(`Server closed on error, port ${PORT} should be freed`);
|
|
369
|
+
});
|
|
370
|
+
}, 100);
|
|
309
371
|
reject(error);
|
|
310
372
|
}
|
|
311
373
|
}
|
|
312
374
|
catch (error) {
|
|
313
375
|
res.status(500).send('Error processing authentication');
|
|
314
|
-
server.
|
|
315
|
-
|
|
316
|
-
}
|
|
376
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
377
|
+
server.closeAllConnections();
|
|
378
|
+
}
|
|
379
|
+
// Use setTimeout to ensure connections are closed before server.close()
|
|
380
|
+
setTimeout(() => {
|
|
381
|
+
server.close(() => {
|
|
382
|
+
// Server closed on error - port should be freed
|
|
383
|
+
log?.debug(`Server closed on error, port ${PORT} should be freed`);
|
|
384
|
+
});
|
|
385
|
+
}, 100);
|
|
386
|
+
reject(error);
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
// Handle server errors (e.g., EADDRINUSE)
|
|
390
|
+
server.on('error', (error) => {
|
|
391
|
+
if (error.code === 'EADDRINUSE') {
|
|
392
|
+
log?.error(`Port ${PORT} is already in use. This should not happen after port check.`);
|
|
393
|
+
reject(new Error(`Port ${PORT} is already in use. Please try again or specify a different port.`));
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
log?.error(`Server error: ${error.message}`);
|
|
317
397
|
reject(error);
|
|
318
398
|
}
|
|
319
399
|
});
|
|
@@ -324,9 +404,16 @@ async function startBrowserAuth(authConfig, browser = 'system', logger, port = 3
|
|
|
324
404
|
// For 'none' browser, don't wait for callback - throw error immediately
|
|
325
405
|
// User must open browser manually and we can't wait for callback in automated tests
|
|
326
406
|
if (serverInstance) {
|
|
327
|
-
server.
|
|
328
|
-
|
|
329
|
-
}
|
|
407
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
408
|
+
server.closeAllConnections();
|
|
409
|
+
}
|
|
410
|
+
// Use setTimeout to ensure connections are closed before server.close()
|
|
411
|
+
setTimeout(() => {
|
|
412
|
+
server.close(() => {
|
|
413
|
+
// Server closed - port should be freed
|
|
414
|
+
log?.debug(`Server closed (browser=none), port ${PORT} should be freed`);
|
|
415
|
+
});
|
|
416
|
+
}, 100);
|
|
330
417
|
}
|
|
331
418
|
reject(new Error(`Browser authentication required. Please open this URL manually: ${authorizationUrl}`));
|
|
332
419
|
return;
|
|
@@ -391,7 +478,17 @@ async function startBrowserAuth(authConfig, browser = 'system', logger, port = 3
|
|
|
391
478
|
}
|
|
392
479
|
}
|
|
393
480
|
catch (error) {
|
|
394
|
-
// If browser cannot be opened,
|
|
481
|
+
// If browser cannot be opened, close server and show URL
|
|
482
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
483
|
+
server.closeAllConnections();
|
|
484
|
+
}
|
|
485
|
+
// Use setTimeout to ensure connections are closed before server.close()
|
|
486
|
+
setTimeout(() => {
|
|
487
|
+
server.close(() => {
|
|
488
|
+
// Server closed on browser open error - port should be freed
|
|
489
|
+
log?.debug(`Server closed on browser open error, port ${PORT} should be freed`);
|
|
490
|
+
});
|
|
491
|
+
}, 100);
|
|
395
492
|
log?.error(`❌ Failed to open browser: ${error?.message || String(error)}. Please open manually: ${authorizationUrl}`, { error: error?.message || String(error), url: authorizationUrl });
|
|
396
493
|
log?.info(`🔗 Open in browser: ${authorizationUrl}`, { url: authorizationUrl });
|
|
397
494
|
// Throw error so consumer can distinguish this from "service key missing" error
|
|
@@ -402,9 +499,16 @@ async function startBrowserAuth(authConfig, browser = 'system', logger, port = 3
|
|
|
402
499
|
// Timeout after 5 minutes
|
|
403
500
|
timeoutId = setTimeout(() => {
|
|
404
501
|
if (serverInstance) {
|
|
405
|
-
server.
|
|
406
|
-
|
|
407
|
-
}
|
|
502
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
503
|
+
server.closeAllConnections();
|
|
504
|
+
}
|
|
505
|
+
// Use setTimeout to ensure connections are closed before server.close()
|
|
506
|
+
setTimeout(() => {
|
|
507
|
+
server.close(() => {
|
|
508
|
+
// Server closed on timeout - port should be freed
|
|
509
|
+
log?.debug(`Server closed on timeout, port ${PORT} should be freed`);
|
|
510
|
+
});
|
|
511
|
+
}, 100);
|
|
408
512
|
reject(new Error('Authentication timeout. Process aborted.'));
|
|
409
513
|
}
|
|
410
514
|
}, 5 * 60 * 1000);
|
package/package.json
CHANGED