@mcp-abap-adt/connection 12.0.0 → 14.0.0

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,761 +0,0 @@
1
- #!/usr/bin/env node
2
- const fs = require("fs");
3
- const path = require("path");
4
- const axios = require("axios");
5
- const { program } = require("commander");
6
- const open = require("open").default;
7
- const http = require("http");
8
-
9
- /**
10
- * Get .env file path
11
- * @param {string} customPath Optional custom path
12
- * @returns {string} Path to .env file
13
- */
14
- function getEnvFilePath(customPath) {
15
- if (customPath) {
16
- return path.resolve(process.cwd(), customPath);
17
- }
18
- return path.resolve(process.cwd(), ".env");
19
- }
20
-
21
- // Browser selection via --browser option (chrome, edge, firefox, system, none)
22
- const BROWSER_MAP = {
23
- chrome: "chrome",
24
- edge: "msedge",
25
- firefox: "firefox",
26
- system: undefined, // system default
27
- none: null, // no browser, manual URL copy
28
- };
29
-
30
- /**
31
- * Reads a JSON service key file
32
- * @param {string} filePath Path to the service key file
33
- * @returns {object} Service key data object
34
- */
35
- function readServiceKey(filePath) {
36
- try {
37
- const fullPath = path.resolve(process.cwd(), filePath);
38
- if (!fs.existsSync(fullPath)) {
39
- console.error(`File not found: ${fullPath}`);
40
- process.exit(1);
41
- }
42
-
43
- const fileContent = fs.readFileSync(fullPath, "utf8");
44
- return JSON.parse(fileContent);
45
- } catch (error) {
46
- console.error(`Error reading service key: ${error.message}`);
47
- process.exit(1);
48
- }
49
- }
50
-
51
- /**
52
- * Reads existing .env file and parses it
53
- * @param {string} envFilePath Path to .env file
54
- * @returns {Object} Parsed .env values
55
- */
56
- function readEnvFile(envFilePath) {
57
- try {
58
- if (!fs.existsSync(envFilePath)) {
59
- return {};
60
- }
61
- const content = fs.readFileSync(envFilePath, "utf8");
62
- const env = {};
63
- content.split("\n").forEach((line) => {
64
- line = line.trim();
65
- if (line && !line.startsWith("#")) {
66
- const [key, ...valueParts] = line.split("=");
67
- if (key && valueParts.length > 0) {
68
- env[key.trim()] = valueParts.join("=").trim();
69
- }
70
- }
71
- });
72
- return env;
73
- } catch (error) {
74
- console.error(`Error reading .env file: ${error.message}`);
75
- return {};
76
- }
77
- }
78
-
79
- /**
80
- * Attempts to refresh JWT token using refresh token
81
- * @param {string} refreshToken Refresh token from .env
82
- * @param {string} uaaUrl UAA URL from .env
83
- * @param {string} clientId UAA client ID from .env
84
- * @param {string} clientSecret UAA client secret from .env
85
- * @returns {Promise<{accessToken: string, refreshToken: string}|null>} New tokens or null if failed
86
- */
87
- async function tryRefreshToken(refreshToken, uaaUrl, clientId, clientSecret) {
88
- try {
89
- console.log("🔄 Attempting to refresh existing JWT token...");
90
- const tokenUrl = `${uaaUrl}/oauth/token`;
91
-
92
- const params = new URLSearchParams();
93
- params.append("grant_type", "refresh_token");
94
- params.append("refresh_token", refreshToken);
95
-
96
- const authString = Buffer.from(`${clientId}:${clientSecret}`).toString("base64");
97
-
98
- const response = await axios({
99
- method: "post",
100
- url: tokenUrl,
101
- headers: {
102
- Authorization: `Basic ${authString}`,
103
- "Content-Type": "application/x-www-form-urlencoded",
104
- },
105
- data: params.toString(),
106
- timeout: 10000, // 10 second timeout
107
- });
108
-
109
- if (response.data && response.data.access_token) {
110
- console.log("✅ Token refreshed successfully!");
111
- return {
112
- accessToken: response.data.access_token,
113
- refreshToken: response.data.refresh_token || refreshToken,
114
- };
115
- }
116
- return null;
117
- } catch (error) {
118
- console.log(`⚠️ Token refresh failed: ${error.message}`);
119
- console.log("📝 Falling back to browser authentication...");
120
- return null;
121
- }
122
- }
123
-
124
- /**
125
- * Decodes JWT token and extracts expiration time
126
- * @param {string} token JWT token string
127
- * @returns {Object|null} Object with expiration date and timestamp, or null if decoding fails
128
- */
129
- function getTokenExpiry(token) {
130
- try {
131
- if (!token) return null;
132
-
133
- // JWT format: header.payload.signature
134
- const parts = token.split('.');
135
- if (parts.length !== 3) return null;
136
-
137
- // Decode payload (base64url)
138
- const payload = parts[1];
139
- // Add padding if needed
140
- const paddedPayload = payload + '='.repeat((4 - payload.length % 4) % 4);
141
- const decodedPayload = Buffer.from(paddedPayload, 'base64').toString('utf8');
142
- const payloadObj = JSON.parse(decodedPayload);
143
-
144
- if (!payloadObj.exp) return null;
145
-
146
- // exp is Unix timestamp in seconds
147
- const expiryTimestamp = payloadObj.exp * 1000; // Convert to milliseconds
148
- const expiryDate = new Date(expiryTimestamp);
149
-
150
- return {
151
- timestamp: expiryTimestamp,
152
- date: expiryDate,
153
- dateString: expiryDate.toISOString(),
154
- readableDate: expiryDate.toLocaleString('en-US', {
155
- timeZone: 'UTC',
156
- dateStyle: 'full',
157
- timeStyle: 'long'
158
- })
159
- };
160
- } catch (error) {
161
- // Silently fail - token might not be a valid JWT or might be in different format
162
- return null;
163
- }
164
- }
165
-
166
- /**
167
- * Updates the .env file with new values
168
- * @param {Object} updates Object with updated values
169
- * @param {string} envFilePath Path to .env file
170
- */
171
- function updateEnvFile(updates, envFilePath) {
172
- try {
173
- // Always remove the old .env file if it exists
174
- if (fs.existsSync(envFilePath)) {
175
- fs.unlinkSync(envFilePath);
176
- }
177
- let lines = [];
178
-
179
- // Get token expiry information
180
- const jwtTokenExpiry = getTokenExpiry(updates.SAP_JWT_TOKEN);
181
- const refreshTokenExpiry = getTokenExpiry(updates.SAP_REFRESH_TOKEN);
182
-
183
- // Add token expiry comments at the beginning if JWT auth
184
- if (updates.SAP_AUTH_TYPE === "jwt") {
185
- lines.push("# Token Expiry Information (auto-generated)");
186
- if (jwtTokenExpiry) {
187
- lines.push(`# JWT Token expires: ${jwtTokenExpiry.readableDate} (UTC)`);
188
- lines.push(`# JWT Token expires at: ${jwtTokenExpiry.dateString}`);
189
- } else {
190
- lines.push("# JWT Token expiry: Unable to determine (token may not be a standard JWT)");
191
- }
192
- if (refreshTokenExpiry) {
193
- lines.push(`# Refresh Token expires: ${refreshTokenExpiry.readableDate} (UTC)`);
194
- lines.push(`# Refresh Token expires at: ${refreshTokenExpiry.dateString}`);
195
- } else if (updates.SAP_REFRESH_TOKEN) {
196
- lines.push("# Refresh Token expiry: Unable to determine (token may not be a standard JWT)");
197
- }
198
- lines.push("");
199
- }
200
-
201
- if (updates.SAP_AUTH_TYPE === "jwt") {
202
- // jwt: write only relevant params
203
- const jwtAllowed = [
204
- "SAP_URL",
205
- "SAP_CLIENT",
206
- "SAP_LANGUAGE",
207
- "TLS_REJECT_UNAUTHORIZED",
208
- "SAP_AUTH_TYPE",
209
- "SAP_JWT_TOKEN",
210
- "SAP_REFRESH_TOKEN",
211
- "SAP_UAA_URL",
212
- "SAP_UAA_CLIENT_ID",
213
- "SAP_UAA_CLIENT_SECRET",
214
- ];
215
- jwtAllowed.forEach((key) => {
216
- if (updates[key]) lines.push(`${key}=${updates[key]}`);
217
- });
218
- lines.push("");
219
- lines.push("# For JWT authentication");
220
- lines.push("# SAP_USERNAME=your_username");
221
- lines.push("# SAP_PASSWORD=your_password");
222
- } else {
223
- // basic: write only relevant params
224
- const basicAllowed = [
225
- "SAP_URL",
226
- "SAP_CLIENT",
227
- "SAP_LANGUAGE",
228
- "TLS_REJECT_UNAUTHORIZED",
229
- "SAP_AUTH_TYPE",
230
- "SAP_USERNAME",
231
- "SAP_PASSWORD",
232
- ];
233
- basicAllowed.forEach((key) => {
234
- if (updates[key]) lines.push(`${key}=${updates[key]}`);
235
- });
236
- lines.push("");
237
- lines.push("# For JWT authentication (not used for basic)");
238
- lines.push("# SAP_JWT_TOKEN=your_jwt_token_here");
239
- }
240
- fs.writeFileSync(envFilePath, lines.join("\n") + "\n", "utf8");
241
- console.log(".env file created successfully.");
242
- } catch (error) {
243
- console.error(`Error updating .env file: ${error.message}`);
244
- process.exit(1);
245
- }
246
- }
247
-
248
- /**
249
- * Builds the JWT (OAuth2) authentication URL
250
- * @param {Object} serviceKey SAP BTP service key object
251
- * @param {number} port Redirect URL port
252
- * @returns {string} Authentication URL
253
- */
254
- function getJwtAuthorizationUrl(serviceKey, port = 3001) {
255
- // Use serviceKey.uaa.url (OAuth endpoint) for OAuth2 authorization URL (correct for BTP ABAP)
256
- const oauthUrl = serviceKey.uaa?.url;
257
- const clientid = serviceKey.uaa?.clientid;
258
- const redirectUri = `http://localhost:${port}/callback`;
259
- return `${oauthUrl}/oauth/authorize?client_id=${encodeURIComponent(
260
- clientid
261
- )}&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}`;
262
- }
263
-
264
- /**
265
- * How long to wait for the browser to come back.
266
- *
267
- * Five minutes was the fixed value, and a real BTP login does not fit in it:
268
- * the identity provider, a password manager and whatever second factor the
269
- * tenant asks for all happen before the redirect is issued. Measured twice —
270
- * both times the window closed first, and the browser then had nowhere to
271
- * redirect to, which reads to the user as the authentication having failed.
272
- *
273
- * So it is a decision the caller makes: `--timeout` in minutes, or
274
- * `SAP_AUTH_TIMEOUT_MS` for a script that would rather not pass an argument.
275
- * The default is fifteen, which covered the login this was measured against
276
- * with room to spare and still bounds a run that has been abandoned.
277
- */
278
- const DEFAULT_AUTH_TIMEOUT_MS = 15 * 60 * 1000;
279
-
280
- function resolveAuthTimeout(minutes) {
281
- if (minutes !== undefined) {
282
- const value = Number(minutes);
283
- if (!Number.isFinite(value) || value <= 0) {
284
- throw new Error(
285
- `--timeout must be a positive number of minutes, got: ${minutes}`
286
- );
287
- }
288
- return value * 60 * 1000;
289
- }
290
- const fromEnv = process.env.SAP_AUTH_TIMEOUT_MS;
291
- if (fromEnv !== undefined && fromEnv !== "") {
292
- const value = Number(fromEnv);
293
- if (!Number.isFinite(value) || value <= 0) {
294
- throw new Error(
295
- `SAP_AUTH_TIMEOUT_MS must be a positive number of milliseconds, got: ${fromEnv}`
296
- );
297
- }
298
- return value;
299
- }
300
- return DEFAULT_AUTH_TIMEOUT_MS;
301
- }
302
-
303
- /**
304
- * One reply, with the header express used to set on our behalf.
305
- *
306
- * `res.send()` chose a Content-Type from what it was handed; `node:http` sends
307
- * exactly what it is told, so the type is stated here. Without it a browser is
308
- * free to render the success page as plain text.
309
- */
310
- function send(res, status, contentType, body) {
311
- res.writeHead(status, { "Content-Type": contentType });
312
- res.end(body);
313
- }
314
-
315
- /**
316
- * Starts a local server to intercept the authentication response
317
- * @param {Object} serviceKey SAP BTP service key object
318
- * @param {string} browser Browser to open
319
- * @param {string} flow Flow type: jwt (OAuth2)
320
- * @returns {Promise<{accessToken: string, refreshToken?: string}>} Promise that resolves to tokens
321
- */
322
- async function startAuthServer(
323
- serviceKey,
324
- browser = undefined,
325
- flow = "jwt",
326
- timeoutMs = DEFAULT_AUTH_TIMEOUT_MS
327
- ) {
328
- return new Promise((resolve, reject) => {
329
- const PORT = 3001;
330
- let serverInstance = null;
331
-
332
- // Choose the authorization URL
333
- const authorizationUrl = getJwtAuthorizationUrl(serviceKey, PORT);
334
-
335
- // JWT OAuth2 flow (get code, exchange for token). One route, and the
336
- // routing express did is two comparisons: a browser fetching /favicon.ico
337
- // must not be mistaken for the redirect we are waiting for.
338
- const server = http.createServer(async (req, res) => {
339
- const url = new URL(req.url, `http://localhost:${PORT}`);
340
- if (req.method !== "GET" || url.pathname !== "/callback") {
341
- send(res, 404, "text/plain; charset=utf-8", "Not Found");
342
- return;
343
- }
344
-
345
- try {
346
- const code = url.searchParams.get("code");
347
- if (!code) {
348
- send(
349
- res,
350
- 400,
351
- "text/plain; charset=utf-8",
352
- "Error: Authorization code missing"
353
- );
354
- return reject(new Error("Authorization code missing"));
355
- }
356
- console.log("Authorization code received");
357
- send(res, 200, "text/html; charset=utf-8", `<!DOCTYPE html>
358
- <html lang="en">
359
- <head>
360
- <meta charset="UTF-8">
361
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
362
- <title>SAP BTP Authentication</title>
363
- <style>
364
- body {
365
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
366
- text-align: center;
367
- margin: 0;
368
- padding: 50px 20px;
369
- background: linear-gradient(135deg, #0070f3 0%, #00d4ff 100%);
370
- color: white;
371
- min-height: 100vh;
372
- display: flex;
373
- flex-direction: column;
374
- justify-content: center;
375
- align-items: center;
376
- }
377
- .container {
378
- background: rgba(255, 255, 255, 0.1);
379
- border-radius: 20px;
380
- padding: 40px;
381
- backdrop-filter: blur(10px);
382
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
383
- max-width: 500px;
384
- width: 100%;
385
- }
386
- .success-icon {
387
- font-size: 4rem;
388
- margin-bottom: 20px;
389
- color: #4ade80;
390
- text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
391
- }
392
- h1 {
393
- margin: 0 0 20px 0;
394
- font-size: 2rem;
395
- font-weight: 300;
396
- }
397
- p {
398
- margin: 0;
399
- font-size: 1.1rem;
400
- opacity: 0.9;
401
- line-height: 1.5;
402
- }
403
- .sap-logo {
404
- margin-top: 30px;
405
- font-weight: bold;
406
- opacity: 0.7;
407
- font-size: 0.9rem;
408
- }
409
- </style>
410
- </head>
411
- <body>
412
- <div class="container">
413
- <div class="success-icon">✓</div>
414
- <h1>Authentication Successful!</h1>
415
- <p>You have successfully authenticated with SAP BTP.</p>
416
- <p>You can now close this browser window.</p>
417
- <div class="sap-logo">SAP Business Technology Platform</div>
418
- </div>
419
- </body>
420
- </html>`);
421
- try {
422
- const tokens = await exchangeCodeForToken(serviceKey, code);
423
- server.close(() => {
424
- console.log("Authentication server stopped");
425
- });
426
- resolve(tokens);
427
- } catch (error) {
428
- reject(error);
429
- }
430
- } catch (error) {
431
- console.error("Error handling callback:", error);
432
- send(
433
- res,
434
- 500,
435
- "text/plain; charset=utf-8",
436
- "Error processing authentication"
437
- );
438
- reject(error);
439
- }
440
- });
441
-
442
- serverInstance = server.listen(PORT, () => {
443
- console.log(`Authentication server started on port ${PORT}`);
444
-
445
- const browserApp = BROWSER_MAP[browser];
446
- if (!browser || browser === "none" || browserApp === null) {
447
- console.log(
448
- "\nBrowser not specified. Please manually open the following URL:"
449
- );
450
- console.log("");
451
- console.log(`🔗 ${authorizationUrl}`);
452
- console.log("");
453
- console.log(
454
- "Copy and paste this URL into your browser to authenticate.\n"
455
- );
456
- } else {
457
- console.log("Opening browser for authentication...");
458
- if (browserApp) {
459
- open(authorizationUrl, { app: { name: browserApp } });
460
- } else {
461
- open(authorizationUrl);
462
- }
463
- }
464
- });
465
-
466
- setTimeout(() => {
467
- if (serverInstance) {
468
- serverInstance.close();
469
- reject(
470
- new Error(
471
- `Authentication timeout after ${
472
- timeoutMs >= 60000
473
- ? `${Math.round(timeoutMs / 60000)} min`
474
- : `${Math.round(timeoutMs / 1000)}s`
475
- }. Process aborted. Raise it with --timeout <minutes> or SAP_AUTH_TIMEOUT_MS if the login needs longer.`
476
- )
477
- );
478
- }
479
- }, timeoutMs);
480
- });
481
- }
482
-
483
- /**
484
- * Exchanges the authorization code for tokens
485
- * @param {Object} serviceKey SAP BTP service key object
486
- * @param {string} code Authorization code
487
- * @returns {Promise<{accessToken: string, refreshToken?: string}>} Promise that resolves to tokens
488
- */
489
- async function exchangeCodeForToken(serviceKey, code) {
490
- try {
491
- const { url, clientid, clientsecret } = serviceKey.uaa;
492
- const tokenUrl = `${url}/oauth/token`;
493
- const redirectUri = "http://localhost:3001/callback";
494
-
495
- const params = new URLSearchParams();
496
- params.append("grant_type", "authorization_code");
497
- params.append("code", code);
498
- params.append("redirect_uri", redirectUri);
499
-
500
- const authString = Buffer.from(`${clientid}:${clientsecret}`).toString(
501
- "base64"
502
- );
503
-
504
- const response = await axios({
505
- method: "post",
506
- url: tokenUrl,
507
- headers: {
508
- Authorization: `Basic ${authString}`,
509
- "Content-Type": "application/x-www-form-urlencoded",
510
- },
511
- data: params.toString(),
512
- });
513
-
514
- if (response.data && response.data.access_token) {
515
- console.log("OAuth token received successfully.");
516
- return {
517
- accessToken: response.data.access_token,
518
- refreshToken: response.data.refresh_token
519
- };
520
- } else {
521
- throw new Error("Response does not contain access_token");
522
- }
523
- } catch (error) {
524
- if (error.response) {
525
- console.error(
526
- `API error (${error.response.status}): ${JSON.stringify(
527
- error.response.data
528
- )}`
529
- );
530
- } else {
531
- console.error(`Error obtaining OAuth token: ${error.message}`);
532
- }
533
- throw error;
534
- }
535
- }
536
-
537
- /**
538
- * Refreshes the access token using refresh token
539
- * @param {Object} serviceKey SAP BTP service key object
540
- * @param {string} refreshToken Refresh token
541
- * @returns {Promise<{accessToken: string, refreshToken?: string}>} Promise that resolves to new tokens
542
- */
543
- async function refreshJwtToken(serviceKey, refreshToken) {
544
- try {
545
- const { url, clientid, clientsecret } = serviceKey.uaa;
546
- const tokenUrl = `${url}/oauth/token`;
547
-
548
- const params = new URLSearchParams();
549
- params.append("grant_type", "refresh_token");
550
- params.append("refresh_token", refreshToken);
551
-
552
- const authString = Buffer.from(`${clientid}:${clientsecret}`).toString(
553
- "base64"
554
- );
555
-
556
- const response = await axios({
557
- method: "post",
558
- url: tokenUrl,
559
- headers: {
560
- Authorization: `Basic ${authString}`,
561
- "Content-Type": "application/x-www-form-urlencoded",
562
- },
563
- data: params.toString(),
564
- });
565
-
566
- if (response.data && response.data.access_token) {
567
- console.log("Access token refreshed successfully.");
568
- return {
569
- accessToken: response.data.access_token,
570
- refreshToken: response.data.refresh_token || refreshToken // Use new refresh token if provided, otherwise keep old one
571
- };
572
- } else {
573
- throw new Error("Response does not contain access_token");
574
- }
575
- } catch (error) {
576
- if (error.response) {
577
- console.error(
578
- `API error (${error.response.status}): ${JSON.stringify(
579
- error.response.data
580
- )}`
581
- );
582
- } else {
583
- console.error(`Error refreshing OAuth token: ${error.message}`);
584
- }
585
- throw error;
586
- }
587
- }
588
-
589
- /**
590
- * Main program function
591
- */
592
- async function main() {
593
- program
594
- .name("sap-abap-auth")
595
- .description(
596
- "CLI utility for authentication in SAP BTP ABAP Environment (Steampunk) via browser. Creates .env file with connection configuration."
597
- )
598
- .version(require("../package.json").version, "-v, --version", "Show version number")
599
- .helpOption("-h, --help", "Show help for all commands and options");
600
-
601
- program
602
- .command("auth")
603
- .description(
604
- "Authenticate in SAP BTP ABAP Environment (Steampunk) via browser and update .env file (JWT)"
605
- )
606
- .requiredOption(
607
- "-k, --key <path>",
608
- "Path to the service key file in JSON format"
609
- )
610
- .option(
611
- "-b, --browser <browser>",
612
- "Browser to open (chrome, edge, firefox, system, none). Use 'none' or omit to display URL for manual copy."
613
- )
614
- .option(
615
- "-o, --output <path>",
616
- "Path to output .env file (default: .env in current directory)"
617
- )
618
- .option(
619
- "-f, --force",
620
- "Force browser authentication even if valid tokens exist in .env"
621
- )
622
- .option(
623
- "-t, --timeout <minutes>",
624
- "How long to wait for the browser redirect, in minutes (default: 15, or SAP_AUTH_TIMEOUT_MS in ms)"
625
- )
626
- .helpOption("-h, --help", "Show help for the auth command")
627
- .action(async (options) => {
628
- try {
629
- if (!options.key) {
630
- console.error(
631
- "Service key file (--key) is required for authentication. Please provide a valid service key JSON file."
632
- );
633
- process.exit(1);
634
- }
635
- console.log("Starting authentication process...");
636
- const serviceKey = readServiceKey(options.key);
637
- console.log("Service key read successfully.");
638
-
639
- // Validate required fields in service key
640
- const abapUrl =
641
- serviceKey.url || serviceKey.abap?.url || serviceKey.sap_url;
642
- if (!abapUrl) {
643
- console.error(
644
- "SAP_URL is missing in the service key. Please check your service key JSON file."
645
- );
646
- process.exit(1);
647
- }
648
-
649
- let tokens = null;
650
-
651
- // Try to refresh existing token if not forced
652
- if (!options.force) {
653
- const envFilePath = getEnvFilePath(options.output);
654
- const existingEnv = readEnvFile(envFilePath);
655
-
656
- // Check if we have all necessary data for token refresh
657
- if (
658
- existingEnv.SAP_REFRESH_TOKEN &&
659
- existingEnv.SAP_UAA_URL &&
660
- existingEnv.SAP_UAA_CLIENT_ID &&
661
- existingEnv.SAP_UAA_CLIENT_SECRET
662
- ) {
663
- tokens = await tryRefreshToken(
664
- existingEnv.SAP_REFRESH_TOKEN,
665
- existingEnv.SAP_UAA_URL,
666
- existingEnv.SAP_UAA_CLIENT_ID,
667
- existingEnv.SAP_UAA_CLIENT_SECRET
668
- );
669
- } else if (existingEnv.SAP_REFRESH_TOKEN) {
670
- console.log("⚠️ Refresh token found in .env but missing UAA credentials");
671
- console.log("📝 Falling back to browser authentication...");
672
- }
673
- } else {
674
- console.log("🔒 Force mode enabled - skipping token refresh");
675
- }
676
-
677
- // Fallback to browser authentication if refresh failed or was skipped
678
- if (!tokens) {
679
- console.log("🌐 Starting browser authentication...");
680
- tokens = await startAuthServer(
681
- serviceKey,
682
- options.browser,
683
- "jwt",
684
- resolveAuthTimeout(options.timeout)
685
- );
686
- if (!tokens || !tokens.accessToken) {
687
- console.error("JWT token was not obtained. Authentication failed.");
688
- process.exit(1);
689
- }
690
- }
691
-
692
- // Collect all relevant parameters from service key
693
- const envUpdates = {
694
- SAP_URL: abapUrl,
695
- TLS_REJECT_UNAUTHORIZED: "0",
696
- SAP_AUTH_TYPE: "jwt",
697
- SAP_JWT_TOKEN: tokens.accessToken,
698
- };
699
-
700
- // Add refresh token if available
701
- if (tokens.refreshToken) {
702
- envUpdates.SAP_REFRESH_TOKEN = tokens.refreshToken;
703
- }
704
-
705
- // Add UAA credentials for token refresh
706
- if (serviceKey.uaa?.url) {
707
- envUpdates.SAP_UAA_URL = serviceKey.uaa.url;
708
- }
709
- if (serviceKey.uaa?.clientid) {
710
- envUpdates.SAP_UAA_CLIENT_ID = serviceKey.uaa.clientid;
711
- }
712
- if (serviceKey.uaa?.clientsecret) {
713
- envUpdates.SAP_UAA_CLIENT_SECRET = serviceKey.uaa.clientsecret;
714
- }
715
- // Optional: client
716
- const abapClient =
717
- serviceKey.client || serviceKey.abap?.client || serviceKey.sap_client;
718
- if (abapClient) {
719
- envUpdates.SAP_CLIENT = abapClient;
720
- }
721
- // Optional: language
722
- if (serviceKey.language) {
723
- envUpdates.SAP_LANGUAGE = serviceKey.language;
724
- } else if (serviceKey.abap && serviceKey.abap.language) {
725
- envUpdates.SAP_LANGUAGE = serviceKey.abap.language;
726
- }
727
-
728
- // Use custom output path if provided
729
- const envFilePath = getEnvFilePath(options.output);
730
- updateEnvFile(envUpdates, envFilePath);
731
- console.log("Authentication completed successfully!");
732
- process.exit(0);
733
- } catch (error) {
734
- console.error(`Error during authentication: ${error.message}`);
735
- process.exit(1);
736
- }
737
- });
738
-
739
- // `version` as a command, like every CLI in the family (`help` is commander's).
740
- program
741
- .command("version")
742
- .description("Show version number")
743
- .action(() => {
744
- console.log(require("../package.json").version);
745
- });
746
-
747
- // Parse and handle command-line arguments
748
- program.parse(process.argv);
749
-
750
- // If no arguments were provided, show help
751
- if (process.argv.length === 2) {
752
- program.help();
753
- }
754
- }
755
-
756
- // Execute the main function
757
- main().catch((error) => {
758
- console.error(`Unexpected error: ${error.message}`);
759
- process.exit(1);
760
- });
761
-