@mcp-abap-adt/connection 13.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.
- package/CHANGELOG.md +18 -1
- package/README.md +2 -61
- package/docs/INDEX.md +4 -8
- package/docs/INSTALLATION.md +2 -38
- package/docs/MIGRATION-14.0.md +17 -0
- package/docs/USAGE.md +0 -1
- package/package.json +2 -8
- package/bin/sap-abap-auth.js +0 -761
- package/docs/JWT_AUTH_TOOLS.md +0 -158
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [14.0.0] - 2026-10-08
|
|
11
|
+
|
|
12
|
+
### Breaking
|
|
13
|
+
|
|
14
|
+
- **The `sap-abap-auth` CLI is removed** (`bin/sap-abap-auth.js`, the `bin`
|
|
15
|
+
field and its `files` entry). It duplicated `@mcp-abap-adt/auth-broker-cli`
|
|
16
|
+
and was authentication logic in a package that does not authenticate. The
|
|
17
|
+
library's API is unchanged. See [MIGRATION-14.0.md](./docs/MIGRATION-14.0.md).
|
|
18
|
+
|
|
19
|
+
### Removed
|
|
20
|
+
|
|
21
|
+
- The CLI, and `docs/JWT_AUTH_TOOLS.md` with it.
|
|
22
|
+
- The runtime dependencies only the CLI used: `open` and `commander`. The
|
|
23
|
+
remaining runtime dependencies are `axios` and the `@mcp-abap-adt` contract
|
|
24
|
+
packages.
|
|
25
|
+
|
|
10
26
|
## [13.0.0] - 2026-10-08
|
|
11
27
|
|
|
12
28
|
12.0.0 was published only on the `next` dist-tag; 13.0.0 is the release that
|
|
@@ -2321,7 +2337,8 @@ const connection = createAbapConnection(config, logger);
|
|
|
2321
2337
|
- JWT token refresh now properly handles connection errors (401/403 during initial connect)
|
|
2322
2338
|
- Permission errors (403 with "ExceptionResourceNoAccess") no longer trigger JWT refresh loops
|
|
2323
2339
|
- Proper separation: base class handles HTTP/session, concrete classes handle auth-specific errors
|
|
2324
|
-
[Unreleased]: https://github.com/fr0ster/mcp-abap-connection/compare/
|
|
2340
|
+
[Unreleased]: https://github.com/fr0ster/mcp-abap-connection/compare/v14.0.0...HEAD
|
|
2341
|
+
[14.0.0]: https://github.com/fr0ster/mcp-abap-connection/compare/v13.0.0...v14.0.0
|
|
2325
2342
|
[13.0.0]: https://github.com/fr0ster/mcp-abap-connection/compare/v12.0.0...v13.0.0
|
|
2326
2343
|
[12.0.0]: https://github.com/fr0ster/mcp-abap-connection/compare/v11.0.1...v12.0.0
|
|
2327
2344
|
[11.0.1]: https://github.com/fr0ster/mcp-abap-connection/compare/v11.0.0...v11.0.1
|
package/README.md
CHANGED
|
@@ -24,7 +24,6 @@ ABAP connection layer for MCP ABAP ADT server. Provides a unified interface for
|
|
|
24
24
|
- Generic `GenericWebSocketTransport` with pluggable WS factory
|
|
25
25
|
- Reusable for debugger/traces and other event-driven flows
|
|
26
26
|
- 📝 **Custom Logging**: Pluggable logger interface for integration with any logging system
|
|
27
|
-
- 🛠️ **CLI Tool**: See [JWT Auth Tools](./docs/JWT_AUTH_TOOLS.md) for obtaining SAP BTP tokens
|
|
28
27
|
- 📦 **TypeScript**: Full TypeScript support with type definitions included
|
|
29
28
|
- ⚡ **Timeout Management**: Configurable timeouts for different operation types
|
|
30
29
|
|
|
@@ -140,7 +139,7 @@ This package interacts with external packages **ONLY through interfaces**:
|
|
|
140
139
|
|
|
141
140
|
The contracts themselves come from five packages, and with `@mcp-abap-adt/auth-errors`
|
|
142
141
|
— the runtime that mints and classifies the auth errors — are the only runtime
|
|
143
|
-
dependencies of this one besides `axios
|
|
142
|
+
dependencies of this one besides `axios`:
|
|
144
143
|
|
|
145
144
|
| Package | What this package takes from it |
|
|
146
145
|
|---|---|
|
|
@@ -161,6 +160,7 @@ the packages above. See [Migration to 9.0.0](./docs/MIGRATION-9.0.md).
|
|
|
161
160
|
|
|
162
161
|
- 📦 **[Installation Guide](./docs/INSTALLATION.md)** - Setup and installation instructions
|
|
163
162
|
- 📚 **[Usage Guide](./docs/USAGE.md)** - Detailed usage examples and API documentation
|
|
163
|
+
- 🚚 **[Migration to 14.0.0](./docs/MIGRATION-14.0.md)** - the `sap-abap-auth` CLI is removed, with its `open` and `commander` dependencies; use `@mcp-abap-adt/auth-broker-cli`; the library's API is unchanged
|
|
164
164
|
- 🚚 **[Migration to 13.0.0](./docs/MIGRATION-13.0.md)** - interfaces-auth 7 and auth-errors 2, and the providers from auth-providers 6.0.0; no behaviour change, one interfaces-auth major per process
|
|
165
165
|
- 🚚 **[Migration to 12.0.0](./docs/MIGRATION-12.0.md)** - refusals follow the auth error contract (interfaces-auth 6, auth-errors): `AuthRefusedError.refusal` is an `IAuthProviderError` — read its `kind`; a custom `ILogonTarget` mints its refusal; no auth-providers release fits 12.x — take 13.0.0 with auth-providers 6.0.0
|
|
166
166
|
- 🚚 **[Migration to 11.0.0](./docs/MIGRATION-11.0.md)** - the server certificate is verified by default; trust a self-signed system with `agentOptions.ca`, or opt out explicitly
|
|
@@ -611,65 +611,6 @@ const connection = new AdtOnPremConnector(
|
|
|
611
611
|
);
|
|
612
612
|
```
|
|
613
613
|
|
|
614
|
-
## CLI Tool
|
|
615
|
-
|
|
616
|
-
The package includes a CLI tool for authenticating with SAP BTP using service keys:
|
|
617
|
-
|
|
618
|
-
### Installation Options
|
|
619
|
-
|
|
620
|
-
- **Local project install**
|
|
621
|
-
```bash
|
|
622
|
-
npm install @mcp-abap-adt/connection --save-dev
|
|
623
|
-
npx sap-abap-auth auth -k path/to/service-key.json
|
|
624
|
-
```
|
|
625
|
-
- **Global install**
|
|
626
|
-
```bash
|
|
627
|
-
npm install -g @mcp-abap-adt/connection
|
|
628
|
-
sap-abap-auth auth -k path/to/service-key.json
|
|
629
|
-
```
|
|
630
|
-
- **On-demand (npx)**
|
|
631
|
-
```bash
|
|
632
|
-
npx @mcp-abap-adt/connection sap-abap-auth auth -k path/to/service-key.json
|
|
633
|
-
```
|
|
634
|
-
|
|
635
|
-
### Usage
|
|
636
|
-
|
|
637
|
-
```bash
|
|
638
|
-
# Show help
|
|
639
|
-
sap-abap-auth --help
|
|
640
|
-
|
|
641
|
-
# Authenticate with service key
|
|
642
|
-
sap-abap-auth auth -k service-key.json
|
|
643
|
-
|
|
644
|
-
# Specify browser
|
|
645
|
-
sap-abap-auth auth -k service-key.json --browser chrome
|
|
646
|
-
|
|
647
|
-
# Custom output file
|
|
648
|
-
sap-abap-auth auth -k service-key.json --output .env.production
|
|
649
|
-
```
|
|
650
|
-
|
|
651
|
-
### Options
|
|
652
|
-
|
|
653
|
-
- `-k, --key <path>` - Path to service key JSON file (required)
|
|
654
|
-
- `-b, --browser <name>` - Browser to open (chrome, edge, firefox, system, none)
|
|
655
|
-
- `-o, --output <path>` - Path to output .env file (default: .env)
|
|
656
|
-
- `-h, --help` - Show help message
|
|
657
|
-
|
|
658
|
-
### Using via `npx` (without global install)
|
|
659
|
-
|
|
660
|
-
If `@mcp-abap-adt/connection` is listed as a dependency in your project, you can invoke the CLI directly:
|
|
661
|
-
|
|
662
|
-
```bash
|
|
663
|
-
npx sap-abap-auth auth -k service-key.json
|
|
664
|
-
```
|
|
665
|
-
|
|
666
|
-
This works even when you do not install the package globally. For one-off usage, you can also run:
|
|
667
|
-
|
|
668
|
-
```bash
|
|
669
|
-
npx @mcp-abap-adt/connection sap-abap-auth auth -k service-key.json
|
|
670
|
-
```
|
|
671
|
-
|
|
672
|
-
This will download the package on demand and execute the CLI.
|
|
673
614
|
## API Reference
|
|
674
615
|
|
|
675
616
|
### Types
|
package/docs/INDEX.md
CHANGED
|
@@ -15,6 +15,7 @@ mcp-abap-connection/
|
|
|
15
15
|
│ ├── INSTALLATION.md # Setup and installation guide
|
|
16
16
|
│ ├── USAGE.md # API documentation and examples
|
|
17
17
|
│ ├── MIGRATION-2.0.md # Moving to the explicit session lifecycle
|
|
18
|
+
│ ├── MIGRATION-14.0.md # the sap-abap-auth CLI, open and commander are removed
|
|
18
19
|
│ ├── MIGRATION-13.0.md # interfaces-auth 7, auth-errors 2, auth-providers 6.0.0; no behaviour change
|
|
19
20
|
│ ├── MIGRATION-12.0.md # refusals follow the auth error contract (interfaces-auth 6, auth-errors)
|
|
20
21
|
│ ├── MIGRATION-11.0.md # the server certificate is verified by default
|
|
@@ -24,13 +25,10 @@ mcp-abap-connection/
|
|
|
24
25
|
│ ├── MIGRATION-6.0.md # the factory and the per-credential classes go; RFC is a transport
|
|
25
26
|
│ ├── MIGRATION-4.0.md # JWT error classification: 401 refreshes, 403 propagates
|
|
26
27
|
│ ├── SCOPE.md # What this package does and does not own
|
|
27
|
-
│
|
|
28
|
-
│ └── JWT_AUTH_TOOLS.md # CLI tool for authentication
|
|
28
|
+
│ └── STATEFUL_SESSION_GUIDE.md # Stateful requests and lock windows
|
|
29
29
|
├── examples/ # Working code examples
|
|
30
30
|
│ ├── README.md # Examples overview
|
|
31
31
|
│ └── basic-connection.js # Simple connection example
|
|
32
|
-
├── bin/ # CLI tools
|
|
33
|
-
│ └── sap-abap-auth.js # JWT authentication CLI
|
|
34
32
|
└── src/ # Source code
|
|
35
33
|
├── connection/ # Connection classes
|
|
36
34
|
├── config/ # Configuration utilities
|
|
@@ -46,10 +44,8 @@ mcp-abap-connection/
|
|
|
46
44
|
- 📖 [Main README](../README.md) - Package overview and quick start
|
|
47
45
|
- 🧭 [Scope and Boundaries](./SCOPE.md) - What this package does (and does not), sibling packages, and why there is no RFC to cloud
|
|
48
46
|
|
|
49
|
-
### Core Features
|
|
50
|
-
- 🔑 [JWT Auth Tools](./JWT_AUTH_TOOLS.md) - CLI tool for browser-based authentication
|
|
51
|
-
|
|
52
47
|
### Upgrading
|
|
48
|
+
- 🚚 [Migrating to 14.0.0](./MIGRATION-14.0.md) - the `sap-abap-auth` CLI is removed; use `@mcp-abap-adt/auth-broker-cli`
|
|
53
49
|
- 🚚 [Migrating to 13.0.0](./MIGRATION-13.0.md) - interfaces-auth 7 and auth-errors 2; the connection's behaviour is unchanged, a consumer holds one interfaces-auth major and takes the providers from auth-providers 6.0.0
|
|
54
50
|
- 🚚 [Migrating to 12.0.0](./MIGRATION-12.0.md) - refusals follow the auth error contract: `AuthRefusedError.refusal` is an `IAuthProviderError` (read its `kind`), a custom `ILogonTarget` mints its refusal through `@mcp-abap-adt/auth-errors`, and no auth-providers release fits 12.x — auth-providers 6.0.0 goes with 13.0.0
|
|
55
51
|
- 🚚 [Migrating to 11.0.0](./MIGRATION-11.0.md) - the server certificate is verified by default; trust a self-signed system with `agentOptions.ca`, or opt out explicitly with `TLS_REJECT_UNAUTHORIZED=0`
|
|
@@ -73,7 +69,7 @@ mcp-abap-connection/
|
|
|
73
69
|
- **Basic Auth**: [USAGE.md - Basic Authentication](./USAGE.md#basic-authentication-on-premise)
|
|
74
70
|
- **JWT/OAuth2**: [USAGE.md - JWT Authentication](./USAGE.md#jwt-authentication-cloudbtp)
|
|
75
71
|
- **Token Refresh**: Handled by `@mcp-abap-adt/auth-broker` package (removed in 0.2.0)
|
|
76
|
-
- **
|
|
72
|
+
- **Obtaining tokens**: `@mcp-abap-adt/auth-broker-cli` (the CLI formerly bundled here was removed in 14.0.0)
|
|
77
73
|
|
|
78
74
|
### Session Management
|
|
79
75
|
- **Overview**: [USAGE.md - Session Management](./USAGE.md#session-management)
|
package/docs/INSTALLATION.md
CHANGED
|
@@ -47,7 +47,7 @@ SAP_PASSWORD=your-password
|
|
|
47
47
|
|
|
48
48
|
### JWT Authentication (SAP BTP Cloud)
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
A `.env` file that carries a JWT can record its expiry as comments, for example:
|
|
51
51
|
|
|
52
52
|
```bash
|
|
53
53
|
# Token Expiry Information (auto-generated)
|
|
@@ -98,42 +98,6 @@ const config = {
|
|
|
98
98
|
};
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
## CLI Tool Installation
|
|
102
|
-
|
|
103
|
-
The package includes `sap-abap-auth` CLI tool for browser-based JWT authentication.
|
|
104
|
-
|
|
105
|
-
### Global Installation
|
|
106
|
-
|
|
107
|
-
```bash
|
|
108
|
-
npm install -g @mcp-abap-adt/connection
|
|
109
|
-
```
|
|
110
|
-
|
|
111
|
-
Then use directly:
|
|
112
|
-
|
|
113
|
-
```bash
|
|
114
|
-
sap-abap-auth auth -k service-key.json
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
### Local Project Installation
|
|
118
|
-
|
|
119
|
-
```bash
|
|
120
|
-
npm install --save-dev @mcp-abap-adt/connection
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
Use via npx:
|
|
124
|
-
|
|
125
|
-
```bash
|
|
126
|
-
npx sap-abap-auth auth -k service-key.json
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
### On-Demand (No Installation)
|
|
130
|
-
|
|
131
|
-
```bash
|
|
132
|
-
npx @mcp-abap-adt/connection sap-abap-auth auth -k service-key.json
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
See [JWT_AUTH_TOOLS.md](./JWT_AUTH_TOOLS.md) for detailed CLI documentation.
|
|
136
|
-
|
|
137
101
|
## Verification
|
|
138
102
|
|
|
139
103
|
### Test Installation
|
|
@@ -384,5 +348,5 @@ read and change the traffic, credentials included. See
|
|
|
384
348
|
- 📚 Read [USAGE.md](./USAGE.md) for detailed usage examples
|
|
385
349
|
- 🔄 Token refresh is handled by `@mcp-abap-adt/auth-broker` package
|
|
386
350
|
- 💾 Session state persistence is handled by `@mcp-abap-adt/auth-broker` package
|
|
387
|
-
- 🔑
|
|
351
|
+
- 🔑 Obtain tokens for SAP BTP with `@mcp-abap-adt/auth-broker-cli`
|
|
388
352
|
- 📖 Review [CHANGELOG.md](../CHANGELOG.md) for version history
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Migration to 14.0
|
|
2
|
+
|
|
3
|
+
14.0.0 removes the bundled `sap-abap-auth` command-line tool, together with the
|
|
4
|
+
two dependencies only it used, `open` and `commander`. The library's API, its
|
|
5
|
+
lifecycle and its behaviour are unchanged.
|
|
6
|
+
|
|
7
|
+
## What a consumer must do
|
|
8
|
+
|
|
9
|
+
- **If you used `sap-abap-auth`** (`npx sap-abap-auth auth -k service-key.json`,
|
|
10
|
+
a global install, or `npx @mcp-abap-adt/connection sap-abap-auth …`): use
|
|
11
|
+
[`@mcp-abap-adt/auth-broker-cli`](https://www.npmjs.com/package/@mcp-abap-adt/auth-broker-cli)
|
|
12
|
+
instead. It provides the `mcp-auth` command (service key to destination) and
|
|
13
|
+
`mcp-sso`; its README lists the options and the `.env` it writes. Its options
|
|
14
|
+
are not those of `sap-abap-auth`, so read it before replacing a script.
|
|
15
|
+
- **If you only used the library**: nothing. You no longer install `open` and
|
|
16
|
+
`commander` through this package; if your code imported either, depend on it
|
|
17
|
+
yourself.
|
package/docs/USAGE.md
CHANGED
|
@@ -1091,5 +1091,4 @@ See [CHANGELOG.md](../CHANGELOG.md) for the version history.
|
|
|
1091
1091
|
|
|
1092
1092
|
- Token refresh functionality is now in `@mcp-abap-adt/auth-broker` package
|
|
1093
1093
|
- Session state persistence is now in `@mcp-abap-adt/auth-broker` package
|
|
1094
|
-
- See [JWT_AUTH_TOOLS.md](./JWT_AUTH_TOOLS.md) for CLI authentication tool
|
|
1095
1094
|
- See [INSTALLATION.md](./INSTALLATION.md) for installation instructions
|
package/package.json
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-abap-adt/connection",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "14.0.0",
|
|
4
4
|
"description": "ABAP connection layer for MCP ABAP ADT server",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"files": [
|
|
8
8
|
"dist",
|
|
9
|
-
"bin",
|
|
10
9
|
"docs",
|
|
11
10
|
"examples",
|
|
12
11
|
"README.md",
|
|
@@ -14,9 +13,6 @@
|
|
|
14
13
|
"LICENSE",
|
|
15
14
|
"COPYING"
|
|
16
15
|
],
|
|
17
|
-
"bin": {
|
|
18
|
-
"sap-abap-auth": "./bin/sap-abap-auth.js"
|
|
19
|
-
},
|
|
20
16
|
"keywords": [
|
|
21
17
|
"abap",
|
|
22
18
|
"sap",
|
|
@@ -59,9 +55,7 @@
|
|
|
59
55
|
"@mcp-abap-adt/interfaces-auth-sap": "^3.3.0",
|
|
60
56
|
"@mcp-abap-adt/interfaces-network": "^2.0.0",
|
|
61
57
|
"@mcp-abap-adt/interfaces-utils": "^1.1.0",
|
|
62
|
-
"axios": "^1.16.0"
|
|
63
|
-
"commander": "^14.0.3",
|
|
64
|
-
"open": "^11.0.0"
|
|
58
|
+
"axios": "^1.16.0"
|
|
65
59
|
},
|
|
66
60
|
"optionalDependencies": {
|
|
67
61
|
"@mcp-abap-adt/sap-rfc-lite": "^0.2.1"
|
package/bin/sap-abap-auth.js
DELETED
|
@@ -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
|
-
|
package/docs/JWT_AUTH_TOOLS.md
DELETED
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
# JWT Auth Tools
|
|
2
|
-
|
|
3
|
-
This package ships with a helper CLI (`sap-abap-auth`) to obtain JWT and refresh tokens for SAP BTP ABAP systems.
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
## Prerequisites
|
|
7
|
-
|
|
8
|
-
- Node.js >= 18
|
|
9
|
-
- Service key JSON for your SAP BTP ABAP instance (from SAP BTP Cockpit)
|
|
10
|
-
- Browser access (for OAuth flow)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
## Quick Start
|
|
14
|
-
|
|
15
|
-
```bash
|
|
16
|
-
npx sap-abap-auth auth -k path/to/service-key.json
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
This launches the OAuth browser flow and prints a `.env` file containing `SAP_JWT_TOKEN`, `SAP_REFRESH_TOKEN`, `SAP_UAA_URL`, etc.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
## Installation Options
|
|
23
|
-
|
|
24
|
-
### Local (Project) Install
|
|
25
|
-
|
|
26
|
-
If `@mcp-abap-adt/connection` is part of your `dependencies` or `devDependencies`, you already have the CLI available:
|
|
27
|
-
|
|
28
|
-
```bash
|
|
29
|
-
npm install @mcp-abap-adt/connection --save-dev
|
|
30
|
-
npx sap-abap-auth auth -k service-key.json
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
Pros:
|
|
34
|
-
- CLI travels with your project.
|
|
35
|
-
- No need for global npm installs.
|
|
36
|
-
|
|
37
|
-
### Global Install
|
|
38
|
-
|
|
39
|
-
```bash
|
|
40
|
-
npm install -g @mcp-abap-adt/connection
|
|
41
|
-
sap-abap-auth auth -k service-key.json
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
Pros:
|
|
45
|
-
- Available system-wide.
|
|
46
|
-
- Useful if you run the tool frequently from the terminal.
|
|
47
|
-
|
|
48
|
-
### On-Demand (One-off) Usage
|
|
49
|
-
|
|
50
|
-
```bash
|
|
51
|
-
npx @mcp-abap-adt/connection sap-abap-auth auth -k service-key.json
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
Pros:
|
|
55
|
-
- No install needed.
|
|
56
|
-
- Perfect for quick usage on CI or temporary machines.
|
|
57
|
-
|
|
58
|
-
## CLI Usage
|
|
59
|
-
|
|
60
|
-
```bash
|
|
61
|
-
# Show help
|
|
62
|
-
sap-abap-auth --help
|
|
63
|
-
|
|
64
|
-
# Authenticate using service key JSON
|
|
65
|
-
sap-abap-auth auth -k service-key.json
|
|
66
|
-
|
|
67
|
-
# Use specific browser (chrome, firefox, edge, system, none)
|
|
68
|
-
sap-abap-auth auth -k service-key.json --browser chrome
|
|
69
|
-
|
|
70
|
-
# Output to custom file (default: .env)
|
|
71
|
-
sap-abap-auth auth -k service-key.json --output .env.production
|
|
72
|
-
|
|
73
|
-
# Print tokens to stdout (no file)
|
|
74
|
-
sap-abap-auth auth -k service-key.json --browser none --output -
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
### Full Command Reference
|
|
78
|
-
|
|
79
|
-
| Option | Description |
|
|
80
|
-
|-------------------------|------------------------------------------------------|
|
|
81
|
-
| `-k, --key <path>` | Path to service key JSON (required) |
|
|
82
|
-
| `-b, --browser <name>` | Browser to open (chrome, edge, firefox, system, none)|
|
|
83
|
-
| `-o, --output <path>` | Output `.env` path (`-` for stdout, defaults to `.env`) |
|
|
84
|
-
| `--config <path>` | Use config file with saved credentials |
|
|
85
|
-
| `--no-open` | Same as `--browser none` |
|
|
86
|
-
| `--help` | Show help |
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
## Using Generated Tokens
|
|
90
|
-
|
|
91
|
-
After running the CLI, you get `.env` similar to:
|
|
92
|
-
|
|
93
|
-
```
|
|
94
|
-
# Token Expiry Information (auto-generated)
|
|
95
|
-
# JWT Token expires: Monday, December 25, 2025 at 10:30:45 AM UTC
|
|
96
|
-
# JWT Token expires at: 2025-12-25T10:30:45.000Z
|
|
97
|
-
# Refresh Token expires: Tuesday, January 25, 2026 at 10:30:45 AM UTC
|
|
98
|
-
# Refresh Token expires at: 2026-01-25T10:30:45.000Z
|
|
99
|
-
|
|
100
|
-
SAP_URL=https://<your-abap-instance>.abap.whatever.sap
|
|
101
|
-
SAP_AUTH_TYPE=jwt
|
|
102
|
-
SAP_JWT_TOKEN=eyJhbGciOi...
|
|
103
|
-
SAP_REFRESH_TOKEN=eyJraWQiOi...
|
|
104
|
-
SAP_UAA_URL=https://<your>-authentication.<region>.hana.ondemand.com/oauth/token
|
|
105
|
-
SAP_UAA_CLIENT_ID=sb-<id>
|
|
106
|
-
SAP_UAA_CLIENT_SECRET=<secret>
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
**Note:** The token expiry information at the top of the `.env` file is automatically generated by decoding the JWT tokens. This helps you:
|
|
110
|
-
- Know when tokens will expire
|
|
111
|
-
- Plan token refresh in advance
|
|
112
|
-
- Troubleshoot authentication issues related to expired tokens
|
|
113
|
-
|
|
114
|
-
If a token's expiry cannot be determined (e.g., non-standard JWT format), a comment will indicate this.
|
|
115
|
-
|
|
116
|
-
Load it in your project:
|
|
117
|
-
|
|
118
|
-
```bash
|
|
119
|
-
source .env
|
|
120
|
-
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
Or configure `SapConfig` directly:
|
|
124
|
-
|
|
125
|
-
```ts
|
|
126
|
-
import {
|
|
127
|
-
AdtCloudConnector,
|
|
128
|
-
CloudHttpTransport,
|
|
129
|
-
} from "@mcp-abap-adt/connection";
|
|
130
|
-
import { TokenAuthProvider } from "@mcp-abap-adt/auth-providers";
|
|
131
|
-
import type { SapConfig } from "@mcp-abap-adt/connection";
|
|
132
|
-
|
|
133
|
-
const config: SapConfig = {
|
|
134
|
-
url: process.env.SAP_URL!,
|
|
135
|
-
authType: "jwt",
|
|
136
|
-
jwtToken: process.env.SAP_JWT_TOKEN!,
|
|
137
|
-
};
|
|
138
|
-
const logger = console;
|
|
139
|
-
|
|
140
|
-
const connection = new AdtCloudConnector(
|
|
141
|
-
config,
|
|
142
|
-
TokenAuthProvider.fixed(config.jwtToken!),
|
|
143
|
-
new CloudHttpTransport(() => ({}), logger, {
|
|
144
|
-
client: config.client,
|
|
145
|
-
baseUrl: config.url,
|
|
146
|
-
}),
|
|
147
|
-
logger,
|
|
148
|
-
);
|
|
149
|
-
|
|
150
|
-
// Note: Token refresh is handled by @mcp-abap-adt/auth-broker package
|
|
151
|
-
// The refresh token credentials in .env are used by auth-broker, not connection
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
## Automating in CI
|
|
156
|
-
|
|
157
|
-
You can run the CLI once locally, store `.env` in secure storage, then load those variables in CI/CD to feed `@mcp-abap-adt/connection`. بهدف
|
|
158
|
-
|