@mcp-abap-adt/connection 15.0.1 → 16.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.
@@ -48,6 +48,10 @@ function hasHeader(headers, name) {
48
48
  * wire's session token and the request's content negotiation.
49
49
  */
50
50
  const OUTRANK_THE_CREDENTIAL = ['x-csrf-token', 'content-type', 'accept'];
51
+ /** What a spent instance answers to `connect()`. Fixed words. */
52
+ function spentError() {
53
+ return (0, SessionLifecycle_js_1.sessionError)(interfaces_adt_connection_1.ADT_SESSION_ERROR.NOT_CONNECTED, "This connection's SAP session has ended (it was disconnected, logged off or lost); one connection instance is one session. Create a new connection for a new session.");
54
+ }
51
55
  class AbstractAbapConnection {
52
56
  config;
53
57
  transport;
@@ -91,10 +95,11 @@ class AbstractAbapConnection {
91
95
  /**
92
96
  * The last goodbye this connection dispatched, so a caller can wait for it.
93
97
  *
94
- * `disconnect()` sends the logoff without awaiting it, for the reason stated
95
- * there. That is right for a teardown and wrong for a caller who is about to
96
- * `connect()` again: the next session opens while the previous one's goodbye
97
- * is still being assembled, and a caller who recycles in a loop leaves one
98
+ * `disconnect()` waits for the logoff to be written, not answered, for the
99
+ * reason stated there. That is right for a teardown and wrong for a caller
100
+ * who is about to `connect()` again: the next session opens while the
101
+ * previous one's goodbye is still unanswered, and a caller who recycles in a
102
+ * loop leaves one
98
103
  * abandoned session per iteration. Measured against E19 from
99
104
  * `@mcp-abap-adt/adt-clients`: a session every 1-2 seconds for a whole test
100
105
  * run, none of them released, each surviving to its 30-minute idle timeout.
@@ -103,6 +108,26 @@ class AbstractAbapConnection {
103
108
  * before this, the promise was created and dropped on the floor.
104
109
  */
105
110
  goodbye = Promise.resolve();
111
+ /**
112
+ * Whether `disconnect()` was called on this instance. A second call
113
+ * rejects: `disconnect()` is called once per instance, and a caller that calls it
114
+ * twice is told so rather than handed a success that waited for nothing.
115
+ */
116
+ disconnectCalled = false;
117
+ /**
118
+ * Whether this instance's one SAP session has ended: it was disconnected,
119
+ * a failed `connect()` logged off the session it had received, or the
120
+ * session was lost (`raiseSessionLost`). One instance is one session —
121
+ * after its logoff it is spent, and `connect()` refuses. A new session is a
122
+ * new instance, which the consumer creates (its own factory, or
123
+ * `createConnection`).
124
+ */
125
+ spent = false;
126
+ /**
127
+ * Every logoff `endSession()` dispatched for this instance, merged: what
128
+ * `disconnect()` waits for (the writes) and `flushGoodbye()` (the answers).
129
+ */
130
+ ended = null;
106
131
  inCriticalSection = false;
107
132
  /** Reference count for nested beginCriticalSection()/endCriticalSection() pairs. */
108
133
  criticalSectionDepth = 0;
@@ -294,8 +319,20 @@ class AbstractAbapConnection {
294
319
  // requested afterwards has already bumped the epoch — and comparing it
295
320
  // against itself would let the connect publish a session the caller had
296
321
  // asked to stop. The baseline is "when the caller asked to connect".
322
+ // One instance is one SAP session: once that session has ended — a
323
+ // disconnect(), a failed connect() that logged it off, or a lost
324
+ // session — the instance is spent, and a new session needs a new
325
+ // instance.
326
+ if (this.spent)
327
+ throw spentError();
297
328
  const baselineEpoch = this.lifecycle.teardownEpoch;
298
329
  await this.lifecycle.transition('connect', async () => {
330
+ // Again here: a disconnect() queued ahead of this connect — called in
331
+ // the same turn, before it — spends the instance only when its
332
+ // transition runs, after the check at entry. Nothing is asked of the
333
+ // credential on a spent instance.
334
+ if (this.spent)
335
+ throw spentError();
299
336
  if (this.lifecycle.connected)
300
337
  return;
301
338
  // Before the wire opens, so that a credential which cannot get ready
@@ -308,8 +345,12 @@ class AbstractAbapConnection {
308
345
  }
309
346
  catch (error) {
310
347
  const rejection = this.credentialRejection(error);
348
+ // A failed establishment that ended a session it had received (a
349
+ // cloud preflight's, say) has spent the instance: no second attempt
350
+ // on it — the original failure is the answer.
311
351
  if (!(error instanceof authErrors_js_1.WireLogonError) ||
312
352
  !rejection ||
353
+ this.spent ||
313
354
  this.lifecycle.teardownEpoch !== baselineEpoch) {
314
355
  throw error;
315
356
  }
@@ -343,12 +384,29 @@ class AbstractAbapConnection {
343
384
  * request cannot use, so the leak surfaces as a half-written object rather
344
385
  * than as anything about sessions.
345
386
  *
346
- * **Nothing is waited for.** The logoff is dispatched, not awaited: this
347
- * method notifies, and whether the server has acted on the notice is not
348
- * something it reports. Finishing chains and releasing locks stay the
349
- * caller's to do BEFORE calling — waiting here on a request that carries no
350
- * timeout by design is what made a teardown unbounded, which blocks every
351
- * later transition on the serialized tail.
387
+ * **Resolves once the logoff is WRITTEN, not answered.** The logoff's bytes
388
+ * handed to the socket (over RFC: the close call returned) is the point a
389
+ * caller needs: SAP queues a logoff behind a request still running in the
390
+ * same stateful ABAP session and answers it only after — ~96 s in one
391
+ * measurement, never in another — yet once it has arrived the ENQUEUE locks
392
+ * go with it, even if the client is killed while waiting for the answer
393
+ * (measured on an on-premise system, 2026-10-12; checked against 16.0.0 on 2026-10-13 with
394
+ * the process exiting right after this resolved: the lock was free ~70 s
395
+ * later, long before the idle timeout). A connection dropped WITHOUT a
396
+ * logoff keeps its locks. So a caller about to exit awaits this, and one
397
+ * that needs the answer awaits `flushGoodbye()` as well. The answer itself
398
+ * is not waited for here, and nothing bounds the write with a timer of its
399
+ * own: a server that never takes the bytes holds this until the socket
400
+ * fails, and that failure is logged, not thrown. Finishing chains and
401
+ * releasing locks stay the caller's to do BEFORE calling.
402
+ *
403
+ * **Called once per `connect()`.** A second call — while the first is still
404
+ * writing, or after it — rejects with `ADT_SESSION_ERROR.NOT_CONNECTED`; the
405
+ * first call is unaffected. A goodbye a failed `connect()` dispatched — to
406
+ * the HTTP security session a connect failing after authentication leaves
407
+ * alive — is written before that
408
+ * `connect()` rejects, so a caller's `disconnect()` in its `finally` is the
409
+ * first of that life and has nothing of it to wait for.
352
410
  *
353
411
  * **Requests already in flight are not waited for, and the logoff ends the
354
412
  * session they are running on** — so they will start failing against a
@@ -357,55 +415,80 @@ class AbstractAbapConnection {
357
415
  * dropped the cookie. Generation fencing (see `SessionLifecycle.isCurrent`)
358
416
  * keeps their results from reaching this connection either way.
359
417
  *
360
- * **Nothing to wait for.** This TELLS the server the session is finished and
361
- * does not act on the answer — whether and when the session is freed is the
362
- * server's affair. Waiting for a reply nobody reads was also the one thing
363
- * that could make a teardown unbounded, since the goodbye carries no request
364
- * timeout by design.
418
+ * **The answer is not waited for.** This TELLS the server the session is
419
+ * finished and does not act on the answer — whether and when the session is
420
+ * freed is the server's affair, and with a request still running in it SAP
421
+ * answers the logoff only once that request is done. Waiting for a reply
422
+ * nobody reads would make a teardown as long as the longest request; the
423
+ * write is what a caller needs, and `flushGoodbye()` is the wait for the
424
+ * answer.
365
425
  */
366
426
  async disconnect() {
367
- // Nothing here throws. This method's place is a `finally` — a connection
368
- // that was connected must be disconnected — and an exception raised there
369
- // replaces the error that sent the caller into it.
427
+ // Called once. A second call — while the first is writing its logoff, or
428
+ // after — rejects, in fixed words: it has nothing to end and nothing to
429
+ // wait for, and resolving would tell a caller about to exit that a logoff
430
+ // it never waited for has left. The first call is unaffected.
431
+ if (this.disconnectCalled) {
432
+ throw (0, SessionLifecycle_js_1.sessionError)(interfaces_adt_connection_1.ADT_SESSION_ERROR.NOT_CONNECTED, 'disconnect() was already called for this connection; call it once per instance');
433
+ }
434
+ this.disconnectCalled = true;
435
+ // Beyond that, nothing here throws. This method's place is a `finally` — a
436
+ // connection that was connected must be disconnected — and an exception
437
+ // raised there replaces the error that sent the caller into it.
438
+ let written = Promise.resolve();
370
439
  // Synchronous, at the call: admission shuts and the generation moves before
371
440
  // anything is queued, so a caller who has asked to disconnect cannot have
372
441
  // requests still going through while this waits its turn.
373
442
  this.lifecycle.beginTeardown({ origin: 'caller', sessionLost: false });
374
443
  await this.lifecycle.transition('disconnect', async () => {
375
- // DISPATCHED, not awaited. The goodbye carries no request timeout by
376
- // design — a server that never answers must not hold a teardown open —
377
- // and nothing bounds it here either, because there is nothing to bound:
378
- // awaiting an unbounded request is precisely what would make every
379
- // teardown unbounded.
444
+ // Dispatched here; awaited below only until it is WRITTEN. The goodbye
445
+ // carries no request timeout by design — a server that never answers
446
+ // must not hold a teardown open — and its answer is not waited for.
380
447
  //
381
448
  // The context is taken now, while the session is still true: the clear
382
449
  // below runs while the close is suspended on its first await.
383
450
  const context = this.sessionContext();
384
451
  // Kept, not dropped: `flushGoodbye()` is how a caller who is about to
385
- // reconnect waits for it. Rejections are absorbed here so that holding
452
+ // open a new connection waits for it. Rejections are absorbed here so that holding
386
453
  // the promise never turns a failed goodbye into an unhandled rejection —
387
454
  // the transport already logs what went wrong.
388
- this.goodbye = this.dispatchGoodbye(context);
455
+ // The terminal teardown: the logoff (when the wire holds a session),
456
+ // the instance spent, and — merged with any logoff the connection
457
+ // already sent on its own — the write the caller waits for and the
458
+ // answer `flushGoodbye()` does.
459
+ written = this.endSession(context).written;
389
460
  this.clearSessionState();
390
461
  this.lifecycle.markDisconnected();
391
462
  });
463
+ // The point this resolves at: the logoff written. Awaited after the
464
+ // transition, so the transition queue — a later connect() — is not held
465
+ // by the write.
466
+ await written;
392
467
  }
393
468
  /**
394
- * Wait for the last dispatched goodbye, bounded.
469
+ * Wait for SAP's answer to the last dispatched goodbye.
395
470
  *
396
471
  * For the caller who ends a session and immediately opens another. Without
397
472
  * it the two overlap and the server keeps both; with it the previous session
398
473
  * is gone — or known not to be going — before the next one is asked for.
399
474
  *
400
- * Bounded because the goodbye deliberately carries no request timeout: a
401
- * server that never answers must not hold a teardown open, and it must not
402
- * hold this open either. On expiry this returns rather than throwing, since
403
- * "the goodbye has not arrived yet" is not a failure of the caller's next
404
- * step — and the session it addressed will fall to the idle timeout anyway.
475
+ * **The bound is the caller's, and optional.** Without `timeoutMs` this waits
476
+ * for the answer as long as it takes, and creates no timer: a timeout of the
477
+ * library's own choosing is not one. With it, this waits at most that long
478
+ * and then returns rather than throwing — "the goodbye has not answered yet"
479
+ * is not a failure of the caller's next step. SAP answers a logoff queued
480
+ * behind a running request only once that request is done (~96 s in one
481
+ * measurement, never in another), so a caller that cannot wait that long
482
+ * passes a budget.
405
483
  *
406
- * Safe to call at any time: with nothing dispatched it returns immediately.
484
+ * Never rejects: a failed goodbye is absorbed. Safe to call at any time:
485
+ * with nothing dispatched it returns immediately.
407
486
  */
408
- async flushGoodbye(timeoutMs = 5000) {
487
+ async flushGoodbye(timeoutMs) {
488
+ if (timeoutMs === undefined) {
489
+ await this.goodbye;
490
+ return;
491
+ }
409
492
  let timer;
410
493
  try {
411
494
  await Promise.race([
@@ -422,6 +505,29 @@ class AbstractAbapConnection {
422
505
  clearTimeout(timer);
423
506
  }
424
507
  }
508
+ /**
509
+ * The one terminal teardown of this instance's session: `disconnect()`, and
510
+ * a failed `connect()` that had received a session.
511
+ *
512
+ * Dispatches the logoff — the wire snapshots its cookies synchronously,
513
+ * without `sap-contextid`, and sends it only when it holds a live
514
+ * `SAP_SESSIONID` — marks the instance spent, and keeps the logoff's write
515
+ * and answer, merged with any earlier one of this instance, for
516
+ * `disconnect()` and `flushGoodbye()`. The caller clears the cookies after.
517
+ */
518
+ endSession(context) {
519
+ const goodbye = this.dispatchGoodbye(context);
520
+ this.spent = true;
521
+ const previous = this.ended;
522
+ this.ended = previous
523
+ ? {
524
+ answered: Promise.all([previous.answered, goodbye.answered]).then(() => { }),
525
+ written: Promise.all([previous.written, goodbye.written]).then(() => { }),
526
+ }
527
+ : goodbye;
528
+ this.goodbye = this.ended.answered;
529
+ return this.ended;
530
+ }
425
531
  /**
426
532
  * Say goodbye to the session `context` describes, without waiting for it.
427
533
  *
@@ -438,16 +544,25 @@ class AbstractAbapConnection {
438
544
  * would send the goodbye without the session it is ending.
439
545
  */
440
546
  dispatchGoodbye(context) {
547
+ let wroteIt;
548
+ const written = new Promise((resolve) => {
549
+ wroteIt = resolve;
550
+ });
441
551
  let closing;
442
552
  try {
443
- closing = Promise.resolve(this.transport.close(context));
553
+ closing = Promise.resolve(this.transport.close(context, () => wroteIt()));
444
554
  }
445
555
  catch (error) {
446
556
  closing = Promise.reject(error);
447
557
  }
448
- return closing.catch((error) => {
558
+ const answered = closing.catch((error) => {
449
559
  this.logger?.debug(`Could not tell the server the session is finished: ${error instanceof Error ? error.message : String(error)}`);
450
560
  });
561
+ // A close that is over is past its write: it sent nothing, it failed to
562
+ // send — logged above, and reported by `answered` settling — or its wire
563
+ // does not tell the write apart (RFC, a custom wire).
564
+ void answered.then(wroteIt);
565
+ return { answered, written };
451
566
  }
452
567
  isConnected() {
453
568
  return this.lifecycle.connected;
@@ -510,6 +625,10 @@ class AbstractAbapConnection {
510
625
  * than written twice — the two would drift apart, as they did once before.
511
626
  */
512
627
  async establishAndCommit(baselineEpoch) {
628
+ // Every establishment attempt, the internal retry included: a spent
629
+ // instance opens no session.
630
+ if (this.spent)
631
+ throw spentError();
513
632
  if (this.lifecycle.teardownEpoch !== baselineEpoch) {
514
633
  throw (0, SessionLifecycle_js_1.sessionError)(interfaces_adt_connection_1.ADT_SESSION_ERROR.NOT_CONNECTED, 'Establishment abandoned: a teardown was requested for this connection');
515
634
  }
@@ -560,15 +679,24 @@ class AbstractAbapConnection {
560
679
  // finished with something we never had sends a request nobody asked for
561
680
  // — into the middle of an authentication exchange, in the case that found
562
681
  // this.
563
- // Whether there is anything to say is the wire's to know: a cloud
564
- // session has an address or it does not, and an on-prem one was
565
- // established or the cookie is debris from the refusal. The connection
566
- // asks, and each wire answers by doing nothing when it has nothing.
682
+ // Whether there is anything to say is the wire's to know, and both
683
+ // shipped wires answer by one rule: a logoff iff they hold a non-empty
684
+ // SAP_SESSIONID they received, whatever the status that brought it — a
685
+ // 404/403 at logon carries one (a live security session), a 401's
686
+ // debris cookie does not. Reached only when connect() as a whole failed:
687
+ // a 404 on core discovery is not that, its fallback runs in the same
688
+ // session. The connection asks, and each wire answers by doing nothing
689
+ // when it has nothing.
567
690
  // Its failure is absorbed, a synchronous throw included: a wire's
568
691
  // close() may reject — its context.authorize throws when the provider
569
692
  // refuses — and nobody awaits this one. A throw that escaped here would
570
693
  // replace the establishment error and skip the clearing below.
571
- const goodbye = this.dispatchGoodbye(this.sessionContext());
694
+ // A session was held — the wire's logoff gate — so this ends it, and
695
+ // the instance is spent; with none held, nothing is sent and connect()
696
+ // may be retried.
697
+ const goodbye = this.transport.sessionFingerprint().size > 0
698
+ ? this.endSession(this.sessionContext())
699
+ : this.dispatchGoodbye(this.sessionContext());
572
700
  this.invalidateSession();
573
701
  // And the identity with it. The rejecting response was still observed, so
574
702
  // its cookie was recorded as a session that had just been established —
@@ -576,10 +704,19 @@ class AbstractAbapConnection {
576
704
  // isConnected() says false. Two answers to one question is worse than
577
705
  // either.
578
706
  this.lifecycle.markDisconnected();
579
- // Not awaited, for the same reason a teardown does not wait: the caller
580
- // is owed the establishment error now, not after a round trip nobody is
581
- // waiting on. Its rejection was absorbed above, so nothing goes unhandled.
582
- void goodbye;
707
+ // The goodbye is the connector's own, so connect() rejects only once it
708
+ // is WRITTEN: a caller that exits on the error must not lose it. When
709
+ // the wire dispatches none (nothing to end), this resolves at once.
710
+ // A failure after authentication leaves a live HTTP security session
711
+ // (ICF, SAP_SESSIONID) on both wires: the cloud preflight opens one
712
+ // (BTP trial, 2026-10-12), and on-prem an authenticated error answer
713
+ // still sets a live SAP_SESSIONID (measured on an on-premise system, 2026-10-13: 404 and
714
+ // 403 each did; ABAP code: CL_HTTP_SERVER_NET->authentication creates
715
+ // it before any handler runs, send_response sets the cookie whatever
716
+ // the status). A failed connect() takes no ENQUEUE lock. The answer is not
717
+ // waited for, as a teardown does not wait for one; its failure was
718
+ // absorbed above, so nothing goes unhandled.
719
+ await goodbye.written;
583
720
  throw error;
584
721
  }
585
722
  if (this.lifecycle.teardownEpoch !== baselineEpoch) {
@@ -630,12 +767,20 @@ class AbstractAbapConnection {
630
767
  // preflight may have opened a session — on cloud it does — and this path
631
768
  // is about to drop the cookies that are the only permission to close it.
632
769
  // Refusing to connect must not leak the session the refusal is about.
633
- // Dispatched, not awaited; a close that throws or rejects is logged and
634
- // absorbed, never left unhandled.
635
- void this.dispatchGoodbye(this.sessionContext());
770
+ // Written before connect() rejects, as above, when the wire sends one.
771
+ // A shipped wire sends none here: this path means the wire holds no
772
+ // SAP_SESSIONID, and without it the logoff would end nothing —
773
+ // CL_HTTP_SERVER_NET->if_http_server~logoff terminates the security
774
+ // session only when that cookie is present (an on-premise system's ABAP code). A custom
775
+ // wire's close() may still send one, and is waited for. Its answer is not waited for, and a close that throws or
776
+ // rejects is logged and absorbed.
777
+ // No session held — that is what this path means — so nothing was
778
+ // logged off, and the instance stays usable: connect() may be retried.
779
+ const goodbye = this.dispatchGoodbye(this.sessionContext());
636
780
  this.invalidateSession();
637
781
  this.lifecycle.forgetIdentity();
638
782
  this.lifecycle.markDisconnected();
783
+ await goodbye.written;
639
784
  throw (0, SessionLifecycle_js_1.sessionError)(interfaces_adt_connection_1.ADT_SESSION_ERROR.NOT_CONNECTED, `The server authenticated the request but opened no ABAP session: the ${this.transport.kind} wire reports it is on none, so there is nothing for a lock to be bound to. The wire itself is fine — the request was carried and answered — which is why this is not a transport failure and does not look like one. ` +
640
785
  'Stateless reads would still work over it, but a lock, and any write under that lock, is dead the moment it is issued. ' +
641
786
  'The usual cause is the system declining to open another session for this user: they are limited per user, shared with every other tool logged on as them, and released either by disconnecting or by their own idle timeout. ' +
@@ -681,6 +826,9 @@ class AbstractAbapConnection {
681
826
  */
682
827
  raiseSessionLost(reason) {
683
828
  this.logger?.warn(`Session lost: ${reason}`);
829
+ // The instance's one session is gone: it is spent, as after disconnect().
830
+ // Nothing else is decided here — the caller is told, and decides.
831
+ this.spent = true;
684
832
  this.lifecycle.beginTeardown({ origin: 'internal', sessionLost: true });
685
833
  void this.lifecycle.transition('cleanup', async () => {
686
834
  this.clearSessionState();
@@ -1046,16 +1194,16 @@ class AbstractAbapConnection {
1046
1194
  return headers;
1047
1195
  }
1048
1196
  /**
1049
- * The wire's own recovery from a failed attempt: the session faults it can
1050
- * cure — a stale CSRF token, a login-form 401 on a mutation, a GET 401 that
1051
- * cookies answer — and the verdicts it must not hide.
1197
+ * The wire's own recovery from a failed attempt: the one fault it can cure
1198
+ * in the same session — a CSRF token SAP refused (a 403 "CSRF token
1199
+ * validation failed", or a 401 to a mutation holding no token yet) — and
1200
+ * the verdicts it must not hide.
1052
1201
  *
1053
- * Runs before anything asks the credential, because it cures session
1054
- * faults, not credential ones: a stale CSRF token under Basic must not
1055
- * become "the user or password was refused". What it cannot cure it throws,
1056
- * and a credential failure among that goes on to the provider. One
1057
- * exception: inside a critical section the login-form 401 is not cured
1058
- * here, because curing it discards the session and the lock with it.
1202
+ * Runs before anything asks the credential: a stale CSRF token under Basic
1203
+ * must not become "the user or password was refused". What it cannot cure
1204
+ * it throws, and a credential failure among that — any other 401, a GET's
1205
+ * included — goes on to the provider. Nothing here resends a 401 as it is,
1206
+ * and nothing discards the session to retry in another.
1059
1207
  *
1060
1208
  * `requestHeaders` are the request's own, without the credential's: what
1061
1209
  * the recovery adds — a new token, the jar's cookies — goes there, and each
@@ -1069,9 +1217,9 @@ class AbstractAbapConnection {
1069
1217
  // Fencing observeResponse() alone was not enough, and the gap was wide:
1070
1218
  // everything below acts on this connection, not on the request. A late
1071
1219
  // 400 "session not found" would call raiseSessionLost() and tear down the
1072
- // healthy session established since; a late 401/403 would call
1073
- // invalidateSession(), write a fresh CSRF token, and RETRY — replaying a
1074
- // mutation from a dead session inside the live one.
1220
+ // healthy session established since; a late 403 would write a fresh CSRF
1221
+ // token and RETRY — replaying a mutation from a dead session inside the
1222
+ // live one.
1075
1223
  //
1076
1224
  // A stale request gets its error back and nothing else happens.
1077
1225
  if (!this.lifecycle.isCurrent(lease)) {
@@ -1111,40 +1259,18 @@ class AbstractAbapConnection {
1111
1259
  else {
1112
1260
  this.logger?.error(errorDetails.message, errorDetails);
1113
1261
  }
1114
- // The "login-form 401": SAP refused a mutation while we hold a cached CSRF
1115
- // token, so the token and the session it is bound to are dead and must be
1116
- // discarded before the retry.
1117
- //
1118
- // These retries cure the session. A 401 that survives them is the
1119
- // credential's, not the session's.
1120
- const isCachedTokenStale = (normalizedMethod === 'POST' ||
1121
- normalizedMethod === 'PUT' ||
1122
- normalizedMethod === 'DELETE') &&
1123
- (0, IAdtTransport_js_1.refusalOf)(error)?.status === 401 &&
1124
- this.getCsrfToken() !== null;
1125
- // Not inside a critical section. Curing the login-form 401 discards the
1126
- // session, and with it the lock the section exists to hold; a renewal
1127
- // must keep it (goal decision 2). There the 401 goes to the provider,
1128
- // whose Ok resends on the same session — and a session SAP really
1129
- // replaced is reported as SESSION_REPLACED from that resend's refusal.
1130
- // Keyed on the section, not the session mode: the write under a lock is
1131
- // itself stateless.
1132
- if (isCachedTokenStale && this.inCriticalSection)
1133
- throw error;
1134
- // Retry logic for CSRF token errors (403 with CSRF message) and the
1135
- // login-form 401 pattern.
1136
- if (this.shouldRetryCsrf(error, normalizedMethod) || isCachedTokenStale) {
1137
- this.logger?.debug(isCachedTokenStale
1138
- ? 'Stale CSRF token / SAP session — invalidating and retrying'
1139
- : 'CSRF token validation failed, fetching new token and retrying request', {
1262
+ // No session is discarded and reopened on this instance to retry a
1263
+ // request: one instance is one session. A 401 on a mutation that holds a
1264
+ // CSRF token (a login form) is not cured here; it goes to the provider
1265
+ // like any other 401, and SAP's answer reaches the caller.
1266
+ // A CSRF complaint (403 "CSRF token validation failed", or a 401 to a
1267
+ // mutation that holds no token yet): a token earned in the SAME session —
1268
+ // the cookies are kept — and one resend.
1269
+ if (this.shouldRetryCsrf(error, normalizedMethod)) {
1270
+ this.logger?.debug('CSRF token validation failed, fetching new token and retrying request', {
1140
1271
  url: requestUrl,
1141
1272
  method: normalizedMethod,
1142
1273
  });
1143
- if (isCachedTokenStale) {
1144
- this.invalidateSession();
1145
- delete requestHeaders.Cookie;
1146
- delete requestHeaders.cookie;
1147
- }
1148
1274
  try {
1149
1275
  this.setCsrfToken(await this.fetchCsrfToken(requestUrl, 5, 2000, lease));
1150
1276
  const refreshedToken = this.getCsrfToken();
@@ -1179,52 +1305,6 @@ class AbstractAbapConnection {
1179
1305
  throw error;
1180
1306
  }
1181
1307
  }
1182
- // A 401 on a GET where cookies have since arrived: the first request had
1183
- // none, and the session they name is what the retry needs. Guarded below
1184
- // on actually holding some, so a wire that issues no cookies — RFC —
1185
- // never takes it.
1186
- if ((0, IAdtTransport_js_1.refusalOf)(error)?.status === 401 && normalizedMethod === 'GET') {
1187
- // If we already have cookies from error response, retry immediately
1188
- const afterError = this.transport.cookies();
1189
- if (afterError) {
1190
- this.logger?.debug(`401 on GET request, retrying with cookies from error response`);
1191
- requestHeaders.Cookie = afterError;
1192
- try {
1193
- requestConfig.headers = await this.authorizedFrom(requestHeaders);
1194
- return await this.sendObserved(requestConfig, lease);
1195
- }
1196
- catch (resendError) {
1197
- throw this.staleOr(resendError, lease);
1198
- }
1199
- }
1200
- // If no cookies, try to get them via CSRF token fetch
1201
- this.logger?.debug(`401 on GET request, attempting to get cookies via CSRF token fetch`);
1202
- try {
1203
- // Try to get CSRF token (this will also get cookies)
1204
- this.setCsrfToken(await this.fetchCsrfToken(requestUrl, 3, 1000, lease));
1205
- const afterCsrf = this.transport.cookies();
1206
- if (afterCsrf) {
1207
- requestHeaders.Cookie = afterCsrf;
1208
- this.logger?.debug(`Retrying GET request with cookies from CSRF fetch`);
1209
- requestConfig.headers = await this.authorizedFrom(requestHeaders);
1210
- return await this.sendObserved(requestConfig, lease);
1211
- }
1212
- }
1213
- catch (csrfError) {
1214
- // As in path (a): a stale request gets the session verdict.
1215
- if (!this.lifecycle.isCurrent(lease)) {
1216
- throw this.staleVerdict(csrfError);
1217
- }
1218
- this.throwIfSessionDead(csrfError, lease);
1219
- // Swallowed, unless it says more than the 401 that started this —
1220
- // a session verdict, or the credential's failure.
1221
- if (this.outranksOriginal(csrfError)) {
1222
- throw csrfError;
1223
- }
1224
- this.logger?.debug(`Failed to get CSRF token for 401 retry: ${csrfError instanceof Error ? csrfError.message : String(csrfError)}`);
1225
- // Fall through to throw original error
1226
- }
1227
- }
1228
1308
  throw error;
1229
1309
  }
1230
1310
  /**
@@ -22,6 +22,13 @@
22
22
  * back to the platform logoff — an inference, and the only one left in this
23
23
  * layer. A consumer that reaches an on-prem system with this transport has
24
24
  * taken the wrong one, and finds out rather than being silently downgraded.
25
+ *
26
+ * **The platform logoff when no link was published.** Not an inference about
27
+ * the system: `/sap/public/bc/icf/logoff` ends a cloud security session too
28
+ * (measured on a BTP trial with bare HTTP, 2026-10-13: a preflight answered
29
+ * without a logoff link yet set a live `SAP_SESSIONID`; after that logoff the
30
+ * same cookies got `401`, before it `200`). So a held session with no link is
31
+ * logged off there, as the on-prem wire does.
25
32
  */
26
33
  import { HttpTransport } from './HttpTransport.js';
27
34
  import type { IAdtSessionContext, ICloudTransport } from './IAdtTransport.js';
@@ -51,7 +58,7 @@ export declare class CloudHttpTransport extends HttpTransport implements ICloudT
51
58
  /** The logoff resource this server linked to beside our session, resolved — the close target. */
52
59
  private logoff;
53
60
  open(context: IAdtSessionContext): Promise<void>;
54
- close(context: IAdtSessionContext): Promise<void>;
61
+ close(context: IAdtSessionContext, written?: () => void): Promise<void>;
55
62
  /**
56
63
  * An href resolved against the document that published it, as a link in an
57
64
  * Atom document is. Resolved at open, so the close has nothing left that can
@@ -1 +1 @@
1
- {"version":3,"file":"CloudHttpTransport.d.ts","sourceRoot":"","sources":["../../src/connection/CloudHttpTransport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAKH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAgB9E,qBAAa,kBACX,SAAQ,aACR,YAAW,eAAe;IAE1B,SAAkB,IAAI,gBAAgB;IAEtC,6EAA6E;IAC7E,QAAQ,CAAC,MAAM,EAAG,OAAO,CAAU;IAEnC;;;;;;;;;;;;;;;;;OAiBG;cACgB,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAI3D,iGAAiG;IACjG,OAAO,CAAC,MAAM,CAAuB;IAEtB,IAAI,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAiEhD,KAAK,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAmChE;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAenB;;;;;OAKG;IACH,OAAO,CAAC,QAAQ;CAWjB"}
1
+ {"version":3,"file":"CloudHttpTransport.d.ts","sourceRoot":"","sources":["../../src/connection/CloudHttpTransport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAKH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAgB9E,qBAAa,kBACX,SAAQ,aACR,YAAW,eAAe;IAE1B,SAAkB,IAAI,gBAAgB;IAEtC,6EAA6E;IAC7E,QAAQ,CAAC,MAAM,EAAG,OAAO,CAAU;IAEnC;;;;;;;;;;;;;;;;;OAiBG;cACgB,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAI3D,iGAAiG;IACjG,OAAO,CAAC,MAAM,CAAuB;IAEtB,IAAI,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAiEhD,KAAK,CAClB,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE,MAAM,IAAI,GACnB,OAAO,CAAC,IAAI,CAAC;IA8ChB;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAenB;;;;;OAKG;IACH,OAAO,CAAC,QAAQ;CAWjB"}