@mcp-abap-adt/connection 5.0.0 → 6.0.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.
Files changed (92) hide show
  1. package/CHANGELOG.md +243 -1
  2. package/README.md +204 -48
  3. package/bin/sap-abap-auth.js +101 -13
  4. package/dist/auth/providers.d.ts +38 -9
  5. package/dist/auth/providers.d.ts.map +1 -1
  6. package/dist/auth/providers.js +46 -3
  7. package/dist/connection/AbstractAbapConnection.d.ts +83 -136
  8. package/dist/connection/AbstractAbapConnection.d.ts.map +1 -1
  9. package/dist/connection/AbstractAbapConnection.js +241 -763
  10. package/dist/connection/AdtCloudConnector.d.ts +12 -7
  11. package/dist/connection/AdtCloudConnector.d.ts.map +1 -1
  12. package/dist/connection/AdtCloudConnector.js +2 -6
  13. package/dist/connection/AdtOnPremConnector.d.ts +20 -7
  14. package/dist/connection/AdtOnPremConnector.d.ts.map +1 -1
  15. package/dist/connection/AdtOnPremConnector.js +2 -6
  16. package/dist/connection/CloudHttpTransport.d.ts +37 -0
  17. package/dist/connection/CloudHttpTransport.d.ts.map +1 -0
  18. package/dist/{session/CloudSecuritySessionStrategy.js → connection/CloudHttpTransport.js} +59 -49
  19. package/dist/connection/CredentialAbapConnection.d.ts +8 -41
  20. package/dist/connection/CredentialAbapConnection.d.ts.map +1 -1
  21. package/dist/connection/CredentialAbapConnection.js +44 -111
  22. package/dist/connection/HttpTransport.d.ts +178 -0
  23. package/dist/connection/HttpTransport.d.ts.map +1 -0
  24. package/dist/connection/HttpTransport.js +402 -0
  25. package/dist/connection/IAdtTransport.d.ts +232 -0
  26. package/dist/connection/IAdtTransport.d.ts.map +1 -0
  27. package/dist/connection/IAdtTransport.js +28 -0
  28. package/dist/connection/LegacyOnPremHttpTransport.d.ts +40 -0
  29. package/dist/connection/LegacyOnPremHttpTransport.d.ts.map +1 -0
  30. package/dist/connection/LegacyOnPremHttpTransport.js +57 -0
  31. package/dist/connection/OnPremHttpTransport.d.ts +45 -0
  32. package/dist/connection/OnPremHttpTransport.d.ts.map +1 -0
  33. package/dist/connection/OnPremHttpTransport.js +91 -0
  34. package/dist/connection/RfcTransport.d.ts +89 -0
  35. package/dist/connection/RfcTransport.d.ts.map +1 -0
  36. package/dist/connection/RfcTransport.js +270 -0
  37. package/dist/connection/rfcConversation.d.ts +44 -0
  38. package/dist/connection/rfcConversation.d.ts.map +1 -0
  39. package/dist/connection/rfcConversation.js +71 -0
  40. package/dist/index.d.ts +7 -8
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +21 -18
  43. package/dist/utils/timeouts.d.ts +6 -19
  44. package/dist/utils/timeouts.d.ts.map +1 -1
  45. package/dist/utils/timeouts.js +6 -22
  46. package/docs/INDEX.md +5 -2
  47. package/docs/INSTALLATION.md +28 -10
  48. package/docs/JWT_AUTH_TOOLS.md +20 -4
  49. package/docs/MIGRATION-6.0.md +359 -0
  50. package/docs/SCOPE.md +1 -1
  51. package/docs/STATEFUL_SESSION_GUIDE.md +86 -17
  52. package/docs/USAGE.md +260 -119
  53. package/examples/basic-connection.js +15 -3
  54. package/examples/jwt-with-token-refresh.js +15 -7
  55. package/examples/saml-connection.js +15 -2
  56. package/package.json +12 -11
  57. package/dist/__tests__/helpers/session.d.ts +0 -15
  58. package/dist/__tests__/helpers/session.d.ts.map +0 -1
  59. package/dist/__tests__/helpers/session.js +0 -19
  60. package/dist/auth/IAuthProvider.d.ts +0 -84
  61. package/dist/auth/IAuthProvider.d.ts.map +0 -1
  62. package/dist/auth/IAuthProvider.js +0 -21
  63. package/dist/connection/BaseAbapConnection.d.ts +0 -29
  64. package/dist/connection/BaseAbapConnection.d.ts.map +0 -1
  65. package/dist/connection/BaseAbapConnection.js +0 -81
  66. package/dist/connection/CertificateAbapConnection.d.ts +0 -35
  67. package/dist/connection/CertificateAbapConnection.d.ts.map +0 -1
  68. package/dist/connection/CertificateAbapConnection.js +0 -91
  69. package/dist/connection/JwtAbapConnection.d.ts +0 -131
  70. package/dist/connection/JwtAbapConnection.d.ts.map +0 -1
  71. package/dist/connection/JwtAbapConnection.js +0 -376
  72. package/dist/connection/KerberosAbapConnection.d.ts +0 -32
  73. package/dist/connection/KerberosAbapConnection.d.ts.map +0 -1
  74. package/dist/connection/KerberosAbapConnection.js +0 -128
  75. package/dist/connection/RfcAbapConnection.d.ts +0 -44
  76. package/dist/connection/RfcAbapConnection.d.ts.map +0 -1
  77. package/dist/connection/RfcAbapConnection.js +0 -324
  78. package/dist/connection/SamlAbapConnection.d.ts +0 -31
  79. package/dist/connection/SamlAbapConnection.d.ts.map +0 -1
  80. package/dist/connection/SamlAbapConnection.js +0 -81
  81. package/dist/connection/connectionFactory.d.ts +0 -25
  82. package/dist/connection/connectionFactory.d.ts.map +0 -1
  83. package/dist/connection/connectionFactory.js +0 -84
  84. package/dist/session/CloudSecuritySessionStrategy.d.ts +0 -32
  85. package/dist/session/CloudSecuritySessionStrategy.d.ts.map +0 -1
  86. package/dist/session/IcfSessionStrategy.d.ts +0 -27
  87. package/dist/session/IcfSessionStrategy.d.ts.map +0 -1
  88. package/dist/session/IcfSessionStrategy.js +0 -62
  89. package/dist/session/SessionStrategy.d.ts +0 -86
  90. package/dist/session/SessionStrategy.d.ts.map +0 -1
  91. package/dist/session/SessionStrategy.js +0 -33
  92. package/docs/superpowers/specs/2026-08-21-platform-connectors.md +0 -108
@@ -1,131 +0,0 @@
1
- import { type IAdtResponse, type ITokenRefresher } from '@mcp-abap-adt/interfaces';
2
- import type { SapConfig } from '../config/sapConfig.js';
3
- import type { ILogger } from '../logger.js';
4
- import type { SessionStrategy } from '../session/SessionStrategy.js';
5
- import type { AbapRequestOptions } from './AbapConnection.js';
6
- import { AbstractAbapConnection } from './AbstractAbapConnection.js';
7
- /**
8
- * The class you take should say which SYSTEM you are dialling, not which
9
- * credential you hold — a session mechanism that rides along with the
10
- * credential gets one of them wrong. `AdtCloudConnector` and
11
- * `AdtOnPremConnector` are how that is said.
12
- *
13
- * **This class is NOT deprecated yet, and must not be replaced by
14
- * `AdtCloudConnector` + `TokenAuthProvider`.** What it does beyond
15
- * authenticating has not moved: a 401 caught mid-operation, one refresh shared
16
- * by every operation in flight, the session rebuilt behind it, generation
17
- * fencing so a dead session's response cannot land, and the request retried
18
- * once. A `TokenAuthProvider` fetches a token at establishment and nothing
19
- * after it, so swapping today trades all of that for a connection that dies on
20
- * the first expiry.
21
- *
22
- * Use this class for JWT until that machinery moves; the split is the
23
- * platform-connectors spec's next step.
24
- */
25
- export declare class JwtAbapConnection extends AbstractAbapConnection {
26
- private tokenRefresher?;
27
- private currentToken;
28
- /** Bumped by any token refresh, token-only ones included. */
29
- private tokenGeneration;
30
- /** Single-flight over the token fetch alone. Touches no session state. */
31
- private tokenRefreshInFlight?;
32
- /**
33
- * The `tokenGeneration` a completed session recovery was built for. Only
34
- * `performRenewal` moves it, and only after `recoverSession` resolves.
35
- *
36
- * Separate from `tokenGeneration` because a token-only refresh — which
37
- * `fetchCsrfToken` does, from inside an establishment — bumps that counter
38
- * without rebuilding anything. Reading it as "the session is settled" made
39
- * the outer handler retry a request whose session was never rebuilt.
40
- */
41
- private recoveredGeneration;
42
- /**
43
- * Single-flight over the whole credential renewal, session included.
44
- *
45
- * Sharing only the token fetch leaves the expensive half racing: `recover`
46
- * and `cleanup` never join (`SessionLifecycle.transition`), so two concurrent
47
- * renewals queue as cleanup A → recover A → cleanup B → recover B, and A's
48
- * retry meets a session B has just torn down.
49
- */
50
- private renewalInFlight?;
51
- /**
52
- * Per connection, deliberately NOT static. `baseline` is compared against
53
- * `this.tokenGeneration`, which is instance state — a store shared between
54
- * instances would let one connection's operation hand its baseline to
55
- * another's, and the comparison would be between unrelated counters.
56
- */
57
- private readonly recoveryScope;
58
- constructor(config: SapConfig, logger?: ILogger | null, sessionId?: string, tokenRefresher?: ITokenRefresher);
59
- protected buildAuthorizationHeader(): string;
60
- /**
61
- * For the public entry point: this call is its own operation, always.
62
- *
63
- * A re-entrant `makeAdtRequest` — from a logger or a refresher callback the
64
- * connection itself invokes while a scope is live — is a new caller-visible
65
- * operation. Inheriting there would hand it a baseline from somebody else's
66
- * refresh, which reads as "already refreshed for me" and skips a refresh it
67
- * needs.
68
- */
69
- private inNewRecoveryScope;
70
- /** For the inner levels: join the operation in progress, or start one. */
71
- private inRecoveryScope;
72
- /**
73
- * The baseline this operation is reasoning from.
74
- *
75
- * The `active` check here and the one in `inRecoveryScope` OVERLAP: each
76
- * compensates for the other, and the stale-context test only fails when both
77
- * are removed. Kept as two because they answer different questions — "may I
78
- * join this scope" and "may I trust this baseline" — and a reader who finds
79
- * one redundant would be deleting half a guarantee.
80
- */
81
- private currentBaseline;
82
- /**
83
- * Fetch a new token, unless somebody already did for this operation.
84
- *
85
- * Single-flighted so two concurrent handlers — including two nested
86
- * `fetchCsrfToken` calls, which is a level `renewalInFlight` cannot reach —
87
- * share one network call instead of racing and leaving `currentToken` as
88
- * whichever settled last.
89
- *
90
- * @returns true when the caller may retry.
91
- */
92
- private refreshTokenOnce;
93
- private performTokenRefresh;
94
- /**
95
- * Renew the credential and the session it belongs to, once, shared.
96
- */
97
- private renewCredential;
98
- private performRenewal;
99
- /**
100
- * May this operation retry?
101
- *
102
- * The order of the checks is the design, not style.
103
- */
104
- private ensureRecovered;
105
- /**
106
- * Establishes the session for this auth type. Called by
107
- * AbstractAbapConnection.connect(), which owns the lifecycle around it.
108
- */
109
- /**
110
- * Cloud manages sessions through ADT: a session resource is opened at
111
- * `/sap/bc/adt/core/http/sessions` and given back by `DELETE` on the address
112
- * the server publishes. This is the one connection that does it — on-prem
113
- * keeps the platform's ICF logoff, which is what it has always used.
114
- */
115
- protected createSessionStrategy(): SessionStrategy;
116
- protected establishSession(): Promise<void>;
117
- /**
118
- * Override makeAdtRequest to handle JWT auth errors with automatic token refresh
119
- */
120
- makeAdtRequest<T = any, D = any>(options: AbapRequestOptions): Promise<IAdtResponse<T, D>>;
121
- private attemptRequest;
122
- /**
123
- * Override fetchCsrfToken to handle JWT auth errors with automatic token refresh
124
- */
125
- protected fetchCsrfToken(url: string, retryCount?: number, retryDelay?: number,
126
- /** Fences the response effects; omitted during connect(), which has no lease. */
127
- generation?: number): Promise<string>;
128
- private attemptCsrfToken;
129
- private static validateConfig;
130
- }
131
- //# sourceMappingURL=JwtAbapConnection.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"JwtAbapConnection.d.ts","sourceRoot":"","sources":["../../src/connection/JwtAbapConnection.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,eAAe,EACrB,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAG5C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAuBrE;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,iBAAkB,SAAQ,sBAAsB;IAC3D,OAAO,CAAC,cAAc,CAAC,CAAkB;IACzC,OAAO,CAAC,YAAY,CAAS;IAE7B,6DAA6D;IAC7D,OAAO,CAAC,eAAe,CAAK;IAE5B,0EAA0E;IAC1E,OAAO,CAAC,oBAAoB,CAAC,CAAmB;IAEhD;;;;;;;;OAQG;IACH,OAAO,CAAC,mBAAmB,CAAK;IAEhC;;;;;;;OAOG;IACH,OAAO,CAAC,eAAe,CAAC,CAAmB;IAE3C;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA2C;gBAGvE,MAAM,EAAE,SAAS,EACjB,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,EACvB,SAAS,CAAC,EAAE,MAAM,EAClB,cAAc,CAAC,EAAE,eAAe;IAWlC,SAAS,CAAC,wBAAwB,IAAI,MAAM;IAW5C;;;;;;;;OAQG;IACH,OAAO,CAAC,kBAAkB;IAc1B,0EAA0E;IAC1E,OAAO,CAAC,eAAe;IASvB;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IAQvB;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;YAsBV,mBAAmB;IAoBjC;;OAEG;IACH,OAAO,CAAC,eAAe;YAiBT,cAAc;IAwB5B;;;;OAIG;YACW,eAAe;IAyB7B;;;OAGG;IACH;;;;;OAKG;cACgB,qBAAqB,IAAI,eAAe;cAI3C,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA4BjD;;OAEG;IACG,cAAc,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EACnC,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YAKhB,cAAc;IA8D5B;;OAEG;cACa,cAAc,CAC5B,GAAG,EAAE,MAAM,EACX,UAAU,GAAE,MAAgC,EAC5C,UAAU,GAAE,MAAgC;IAC5C,iFAAiF;IACjF,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,CAAC;YASJ,gBAAgB;IAkD9B,OAAO,CAAC,MAAM,CAAC,cAAc;CAa9B"}
@@ -1,376 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.JwtAbapConnection = void 0;
4
- const node_async_hooks_1 = require("node:async_hooks");
5
- const interfaces_1 = require("@mcp-abap-adt/interfaces");
6
- const axios_1 = require("axios");
7
- const CloudSecuritySessionStrategy_js_1 = require("../session/CloudSecuritySessionStrategy.js");
8
- const SessionLifecycle_js_1 = require("../session/SessionLifecycle.js");
9
- const AbstractAbapConnection_js_1 = require("./AbstractAbapConnection.js");
10
- const csrfConfig_js_1 = require("./csrfConfig.js");
11
- /**
12
- * Is this worth refreshing a token for?
13
- *
14
- * 401 only. A 403 means the server authenticated the caller and refused the
15
- * action anyway — a new token is the same caller, so refreshing answers a
16
- * question nobody asked and, worse, used to end with the original error
17
- * replaced by "JWT token has expired". See issue #30.
18
- */
19
- function isTokenExpiryCandidate(error) {
20
- return error instanceof axios_1.AxiosError && error.response?.status === 401;
21
- }
22
- /**
23
- * The class you take should say which SYSTEM you are dialling, not which
24
- * credential you hold — a session mechanism that rides along with the
25
- * credential gets one of them wrong. `AdtCloudConnector` and
26
- * `AdtOnPremConnector` are how that is said.
27
- *
28
- * **This class is NOT deprecated yet, and must not be replaced by
29
- * `AdtCloudConnector` + `TokenAuthProvider`.** What it does beyond
30
- * authenticating has not moved: a 401 caught mid-operation, one refresh shared
31
- * by every operation in flight, the session rebuilt behind it, generation
32
- * fencing so a dead session's response cannot land, and the request retried
33
- * once. A `TokenAuthProvider` fetches a token at establishment and nothing
34
- * after it, so swapping today trades all of that for a connection that dies on
35
- * the first expiry.
36
- *
37
- * Use this class for JWT until that machinery moves; the split is the
38
- * platform-connectors spec's next step.
39
- */
40
- class JwtAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapConnection {
41
- tokenRefresher;
42
- currentToken;
43
- /** Bumped by any token refresh, token-only ones included. */
44
- tokenGeneration = 0;
45
- /** Single-flight over the token fetch alone. Touches no session state. */
46
- tokenRefreshInFlight;
47
- /**
48
- * The `tokenGeneration` a completed session recovery was built for. Only
49
- * `performRenewal` moves it, and only after `recoverSession` resolves.
50
- *
51
- * Separate from `tokenGeneration` because a token-only refresh — which
52
- * `fetchCsrfToken` does, from inside an establishment — bumps that counter
53
- * without rebuilding anything. Reading it as "the session is settled" made
54
- * the outer handler retry a request whose session was never rebuilt.
55
- */
56
- recoveredGeneration = 0;
57
- /**
58
- * Single-flight over the whole credential renewal, session included.
59
- *
60
- * Sharing only the token fetch leaves the expensive half racing: `recover`
61
- * and `cleanup` never join (`SessionLifecycle.transition`), so two concurrent
62
- * renewals queue as cleanup A → recover A → cleanup B → recover B, and A's
63
- * retry meets a session B has just torn down.
64
- */
65
- renewalInFlight;
66
- /**
67
- * Per connection, deliberately NOT static. `baseline` is compared against
68
- * `this.tokenGeneration`, which is instance state — a store shared between
69
- * instances would let one connection's operation hand its baseline to
70
- * another's, and the comparison would be between unrelated counters.
71
- */
72
- recoveryScope = new node_async_hooks_1.AsyncLocalStorage();
73
- constructor(config, logger, sessionId, tokenRefresher) {
74
- JwtAbapConnection.validateConfig(config);
75
- super(config, logger || null, sessionId);
76
- this.tokenRefresher = tokenRefresher;
77
- if (!config.jwtToken) {
78
- throw new Error('jwtToken is required for JwtAbapConnection');
79
- }
80
- this.currentToken = config.jwtToken;
81
- }
82
- buildAuthorizationHeader() {
83
- // Use currentToken which may have been refreshed
84
- const tokenPreview = this.currentToken
85
- ? `${this.currentToken.substring(0, 10)}...${this.currentToken.substring(Math.max(0, this.currentToken.length - 4))}`
86
- : 'null';
87
- this.logger?.debug(`[DEBUG] JwtAbapConnection.buildAuthorizationHeader - Using token: ${tokenPreview}`);
88
- return `Bearer ${this.currentToken}`;
89
- }
90
- /**
91
- * For the public entry point: this call is its own operation, always.
92
- *
93
- * A re-entrant `makeAdtRequest` — from a logger or a refresher callback the
94
- * connection itself invokes while a scope is live — is a new caller-visible
95
- * operation. Inheriting there would hand it a baseline from somebody else's
96
- * refresh, which reads as "already refreshed for me" and skips a refresh it
97
- * needs.
98
- */
99
- inNewRecoveryScope(fn) {
100
- const scope = {
101
- baseline: this.tokenGeneration,
102
- active: true,
103
- };
104
- return this.recoveryScope.run(scope, async () => {
105
- try {
106
- return await fn();
107
- }
108
- finally {
109
- scope.active = false;
110
- }
111
- });
112
- }
113
- /** For the inner levels: join the operation in progress, or start one. */
114
- inRecoveryScope(fn) {
115
- const inherited = this.recoveryScope.getStore();
116
- // Only a scope that is still running. A store reached through an async
117
- // resource that outlived its operation is stale, and its baseline describes
118
- // a credential state that has since moved.
119
- if (inherited?.active)
120
- return fn();
121
- return this.inNewRecoveryScope(fn);
122
- }
123
- /**
124
- * The baseline this operation is reasoning from.
125
- *
126
- * The `active` check here and the one in `inRecoveryScope` OVERLAP: each
127
- * compensates for the other, and the stale-context test only fails when both
128
- * are removed. Kept as two because they answer different questions — "may I
129
- * join this scope" and "may I trust this baseline" — and a reader who finds
130
- * one redundant would be deleting half a guarantee.
131
- */
132
- currentBaseline() {
133
- const scope = this.recoveryScope.getStore();
134
- // No live scope means a caller reached a handler by a path that does not
135
- // open one, or through a stale async context. Either way, treat it as its
136
- // own operation rather than trusting a baseline nobody is standing behind.
137
- return scope?.active ? scope.baseline : this.tokenGeneration;
138
- }
139
- /**
140
- * Fetch a new token, unless somebody already did for this operation.
141
- *
142
- * Single-flighted so two concurrent handlers — including two nested
143
- * `fetchCsrfToken` calls, which is a level `renewalInFlight` cannot reach —
144
- * share one network call instead of racing and leaving `currentToken` as
145
- * whichever settled last.
146
- *
147
- * @returns true when the caller may retry.
148
- */
149
- refreshTokenOnce(baseline) {
150
- if (this.tokenGeneration > baseline)
151
- return Promise.resolve(true);
152
- if (this.tokenRefreshInFlight)
153
- return this.tokenRefreshInFlight;
154
- if (!this.tokenRefresher) {
155
- this.logger?.debug(`[DEBUG] JwtAbapConnection - No tokenRefresher available, cannot refresh token`);
156
- return Promise.resolve(false);
157
- }
158
- // Identity-checked clear, as SessionLifecycle.transition does with its
159
- // tail: a joiner settling late must not clear a fetch somebody started
160
- // after it.
161
- const inFlight = this.performTokenRefresh().finally(() => {
162
- if (this.tokenRefreshInFlight === inFlight) {
163
- this.tokenRefreshInFlight = undefined;
164
- }
165
- });
166
- this.tokenRefreshInFlight = inFlight;
167
- return inFlight;
168
- }
169
- async performTokenRefresh() {
170
- try {
171
- this.logger?.debug(`[DEBUG] JwtAbapConnection - Refreshing token via tokenRefresher...`);
172
- // biome-ignore lint/style/noNonNullAssertion: refreshTokenOnce checks it
173
- this.currentToken = await this.tokenRefresher.refreshToken();
174
- this.tokenGeneration += 1;
175
- this.logger?.debug(`[DEBUG] JwtAbapConnection - Token refreshed successfully`);
176
- return true;
177
- }
178
- catch (error) {
179
- this.logger?.error(`[ERROR] JwtAbapConnection - Failed to refresh token: ${error instanceof Error ? error.message : String(error)}`);
180
- return false;
181
- }
182
- }
183
- /**
184
- * Renew the credential and the session it belongs to, once, shared.
185
- */
186
- renewCredential(baselineEpoch, baseline) {
187
- if (this.renewalInFlight)
188
- return this.renewalInFlight;
189
- // Identity-checked clear, as SessionLifecycle.transition does with its
190
- // tail: a joiner settling late must not clear a renewal somebody started
191
- // after it.
192
- const inFlight = this.performRenewal(baselineEpoch, baseline).finally(() => {
193
- if (this.renewalInFlight === inFlight)
194
- this.renewalInFlight = undefined;
195
- });
196
- this.renewalInFlight = inFlight;
197
- return inFlight;
198
- }
199
- async performRenewal(baselineEpoch, baseline) {
200
- // Shared with the token-only path, and a no-op when the token is already
201
- // newer than the one that failed — then what is missing is the session, and
202
- // a second fetch answers a question nobody asked.
203
- if (!(await this.refreshTokenOnce(baseline)))
204
- return false;
205
- this.logger?.debug(`[DEBUG] JwtAbapConnection - Recovering session after token refresh...`);
206
- // The renewed credential cannot keep the old ABAP session, so this is a
207
- // session-lost teardown — internal, or it would cancel the very recovery it
208
- // is setting up. disconnect() would be the caller-origin one.
209
- this.discardSession();
210
- // Re-establish before retrying: the retry goes through admission, and a
211
- // discarded session admits nothing.
212
- await this.recoverSession(baselineEpoch);
213
- // Only here: a session now exists that was built with this token.
214
- this.recoveredGeneration = this.tokenGeneration;
215
- return true;
216
- }
217
- /**
218
- * May this operation retry?
219
- *
220
- * The order of the checks is the design, not style.
221
- */
222
- async ensureRecovered(baselineEpoch) {
223
- // 1. A renewal in flight is joined REGARDLESS of generation. A newer token
224
- // is no use while the session it belongs to is still being rebuilt:
225
- // retrying now is how a caller meets a closed admission door.
226
- //
227
- // This overlaps check 2 as the counters stand — `recoveredGeneration`
228
- // only moves after `recoverSession` resolves, so check 2 cannot report a
229
- // rebuild that has not finished, and removing either guard alone leaves
230
- // the concurrency test green. Both are kept on purpose: this one states
231
- // the rule ("never decide anything while a renewal is running") without
232
- // depending on when some other counter happens to move, and it is what
233
- // keeps the invariant true if check 2's counter is ever changed.
234
- if (this.renewalInFlight)
235
- return this.renewalInFlight;
236
- const baseline = this.currentBaseline();
237
- // 2. A full renewal COMPLETED since this operation began — token, and the
238
- // session built with it. Not `tokenGeneration`: that moves on a
239
- // token-only refresh, which rebuilds nothing.
240
- if (this.recoveredGeneration > baseline)
241
- return true;
242
- // 3. Nobody has. Renew, and let everyone else join.
243
- return this.renewCredential(baselineEpoch, baseline);
244
- }
245
- /**
246
- * Establishes the session for this auth type. Called by
247
- * AbstractAbapConnection.connect(), which owns the lifecycle around it.
248
- */
249
- /**
250
- * Cloud manages sessions through ADT: a session resource is opened at
251
- * `/sap/bc/adt/core/http/sessions` and given back by `DELETE` on the address
252
- * the server publishes. This is the one connection that does it — on-prem
253
- * keeps the platform's ICF logoff, which is what it has always used.
254
- */
255
- createSessionStrategy() {
256
- return new CloudSecuritySessionStrategy_js_1.CloudSecuritySessionStrategy(this.logger);
257
- }
258
- async establishSession() {
259
- const baseUrl = await this.getBaseUrl();
260
- const discoveryUrl = `${baseUrl}/sap/bc/adt/discovery`;
261
- this.logger?.debug(`[DEBUG] JwtAbapConnection - Connecting to SAP system: ${discoveryUrl}`);
262
- try {
263
- // Try to get CSRF token (this will also get cookies)
264
- const token = await this.fetchCsrfToken(discoveryUrl);
265
- this.setCsrfToken(token);
266
- this.logger?.debug('Successfully connected to SAP system', {
267
- hasCsrfToken: !!this.getCsrfToken(),
268
- hasCookies: !!this.getCookies(),
269
- cookieLength: this.getCookies()?.length || 0,
270
- });
271
- }
272
- catch (error) {
273
- if (isTokenExpiryCandidate(error)) {
274
- this.logger?.error('[ERROR] JwtAbapConnection.establishSession - 401 while establishing; fetchCsrfToken has already refreshed and retried for this');
275
- }
276
- throw error;
277
- }
278
- }
279
- /**
280
- * Override makeAdtRequest to handle JWT auth errors with automatic token refresh
281
- */
282
- async makeAdtRequest(options) {
283
- // A public call is its own operation, whatever scope it starts in.
284
- return this.inNewRecoveryScope(() => this.attemptRequest(options));
285
- }
286
- async attemptRequest(options) {
287
- // Captured before the attempt: a recovery asks "has the caller asked to
288
- // stop since this request began", not since some later bookkeeping step.
289
- const baselineEpoch = this.teardownEpoch;
290
- this.logger?.debug(`[DEBUG] JwtAbapConnection.makeAdtRequest - Starting request: ${options.method} ${options.url}`);
291
- try {
292
- const response = await super.makeAdtRequest(options);
293
- this.logger?.debug(`[DEBUG] JwtAbapConnection.makeAdtRequest - Request succeeded: ${response.status}`);
294
- return response;
295
- }
296
- catch (error) {
297
- this.logger?.debug(`[DEBUG] JwtAbapConnection.makeAdtRequest - Request failed: ${error instanceof Error ? error.message : String(error)}`);
298
- if (isTokenExpiryCandidate(error)) {
299
- this.logger?.debug(`[DEBUG] JwtAbapConnection.makeAdtRequest - Got 401, attempting token refresh...`);
300
- if (await this.ensureRecovered(baselineEpoch)) {
301
- // A renewal this operation joined was fenced against the STARTER's
302
- // baseline, not this one's, and establishAndCommit's own epoch checks
303
- // belong to the establishment that ran. Between the last of them and
304
- // this retry there is a gap nothing else watches: the connection can
305
- // be torn down by its caller and made usable again, and a retry would
306
- // then go out on a session that caller discarded.
307
- if (this.teardownEpoch !== baselineEpoch) {
308
- throw (0, SessionLifecycle_js_1.sessionError)(interfaces_1.ADT_SESSION_ERROR.NOT_CONNECTED, 'Retry abandoned: a teardown was requested for this connection');
309
- }
310
- try {
311
- return await super.makeAdtRequest(options);
312
- }
313
- catch (retryError) {
314
- // A 401 that survived a renewal is the case the deleted message
315
- // was about, and it only shows up here — the log below fires when
316
- // the renewal never happened, which is a different fact.
317
- if (isTokenExpiryCandidate(retryError)) {
318
- this.logger?.error('[ERROR] JwtAbapConnection.makeAdtRequest - 401 persists after a credential renewal; the credential may need re-authentication');
319
- }
320
- throw retryError;
321
- }
322
- }
323
- this.logger?.error('[ERROR] JwtAbapConnection.makeAdtRequest - 401 persists and the token could not be refreshed; the credential may need re-authentication');
324
- }
325
- throw error;
326
- }
327
- }
328
- /**
329
- * Override fetchCsrfToken to handle JWT auth errors with automatic token refresh
330
- */
331
- async fetchCsrfToken(url, retryCount = csrfConfig_js_1.CSRF_CONFIG.RETRY_COUNT, retryDelay = csrfConfig_js_1.CSRF_CONFIG.RETRY_DELAY,
332
- /** Fences the response effects; omitted during connect(), which has no lease. */
333
- generation) {
334
- // An inner level: join the operation in progress, or start one when
335
- // reached directly — a bare connect() is still an operation with a
336
- // baseline.
337
- return this.inRecoveryScope(() => this.attemptCsrfToken(url, retryCount, retryDelay, generation));
338
- }
339
- async attemptCsrfToken(url, retryCount, retryDelay, generation) {
340
- try {
341
- // Try to fetch CSRF token using parent implementation
342
- return await super.fetchCsrfToken(url, retryCount, retryDelay, generation);
343
- }
344
- catch (error) {
345
- // A 401 here may be an expired token; anything else is not ours to
346
- // interpret — a 403 least of all, since a new token is the same caller.
347
- if (isTokenExpiryCandidate(error)) {
348
- if (await this.refreshTokenOnce(this.currentBaseline())) {
349
- // Retry CSRF token fetch with new token
350
- this.logger?.debug(`[DEBUG] JwtAbapConnection.fetchCsrfToken - Retrying after token refresh...`);
351
- try {
352
- return await super.fetchCsrfToken(url, retryCount, retryDelay, generation);
353
- }
354
- catch (retryError) {
355
- if (isTokenExpiryCandidate(retryError)) {
356
- this.logger?.error('[ERROR] JwtAbapConnection.fetchCsrfToken - 401 persists after a token refresh; the credential may need re-authentication');
357
- }
358
- throw retryError;
359
- }
360
- }
361
- this.logger?.error('[ERROR] JwtAbapConnection.fetchCsrfToken - 401 persists and the token could not be refreshed; the credential may need re-authentication');
362
- }
363
- // Re-throw other errors
364
- throw error;
365
- }
366
- }
367
- static validateConfig(config) {
368
- if (config.authType !== 'jwt') {
369
- throw new Error(`JWT connection expects authType "jwt", got "${config.authType}"`);
370
- }
371
- if (!config.jwtToken) {
372
- throw new Error('JWT authentication requires SAP_JWT_TOKEN to be provided');
373
- }
374
- }
375
- }
376
- exports.JwtAbapConnection = JwtAbapConnection;
@@ -1,32 +0,0 @@
1
- import type { SapConfig } from '../config/sapConfig.js';
2
- import type { ILogger } from '../logger.js';
3
- import { AbstractAbapConnection } from './AbstractAbapConnection.js';
4
- /**
5
- * @deprecated The class you take should say which SYSTEM you are dialling,
6
- * not which credential you hold — a session mechanism that rides along with
7
- * the credential gets one of them wrong. Use `AdtOnPremConnector` with `a Kerberos credential`:
8
- *
9
- * not yet available — SPNEGO keeps its own class until its exchange is moved
10
- *
11
- * Kept working, and not removed here: existing consumers are unaffected.
12
- */
13
- export declare class KerberosAbapConnection extends AbstractAbapConnection {
14
- private spn;
15
- private currentToken;
16
- constructor(config: SapConfig, logger?: ILogger | null, sessionId?: string);
17
- private static validateConfig;
18
- /** Generate the SPNEGO token once (single-leg). */
19
- protected ensureToken(): Promise<void>;
20
- /**
21
- * Generates the SPNEGO token and primes the session. MUST be called before the first
22
- * request — the first request carries the Negotiate header; SAP then issues a session
23
- * cookie which is reused for subsequent requests.
24
- */
25
- /**
26
- * Establishes the session for this auth type. Called by
27
- * AbstractAbapConnection.connect(), which owns the lifecycle around it.
28
- */
29
- protected establishSession(): Promise<void>;
30
- protected buildAuthorizationHeader(): string;
31
- }
32
- //# sourceMappingURL=KerberosAbapConnection.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"KerberosAbapConnection.d.ts","sourceRoot":"","sources":["../../src/connection/KerberosAbapConnection.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAErE;;;;;;;;GAQG;AACH,qBAAa,sBAAuB,SAAQ,sBAAsB;IAChE,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,YAAY,CAAM;gBAEd,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,EAAE,SAAS,CAAC,EAAE,MAAM;IAQ1E,OAAO,CAAC,MAAM,CAAC,cAAc;IAa7B,mDAAmD;cACnC,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5C;;;;OAIG;IACH;;;OAGG;cACa,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IAqFjD,SAAS,CAAC,wBAAwB,IAAI,MAAM;CAS7C"}