@mcp-abap-adt/auth-providers
v8.0.1
Published
Every IAuthProvider for SAP ABAP ADT: the credentials a process delegates to, and the token providers behind them
Maintainers
Readme
@mcp-abap-adt/auth-providers
Every implementation of IAuthProvider for SAP ABAP ADT: the credential a
process delegates to, and the token providers behind it.
Token providers, the Basic/Certificate/SAML/Token credentials, passwordless
SNC logon and SPNego (Kerberos) over HTTP are each an IAuthProvider the process takes as it is — whether it
is handed over directly to a connection, or through
@mcp-abap-adt/auth-broker for the stateful token API
(getTokens()/refreshTokens()).
Migrating to 8.0.0 — static types first
8.0.0 checks at runtime only what the TypeScript types cannot say. Options
and collaborators are trusted to match their types. What comes from outside
the type system is checked as before: a thrown value, a server's answer, a
JWT, a SAML document, a file, the environment, registry output, terminal
input, a callback request, GSS token bytes, a field a contract types
unknown. No refusal, kind, case or operation is new; every refusal still
produced keeps its words, facts and kind; the dependencies are unchanged.
What a consumer on 7.x must do:
- Pass options and collaborators that type-check. A TypeScript consumer whose code compiles against 8.0.0 needs nothing else. A JavaScript consumer, or one that casts, no longer gets a configuration refusal for a value of the wrong type; what a constructor does with such a value is not stated.
- Options are a typed copy. Each constructor and factory copies its options once, with a shallow spread, instead of reading their own data properties: a getter on the options runs once, at creation (7.x read it as absent). A later change to your object still changes nothing. See Error Handling.
- These configuration refusals are no longer produced. The cases stay on
interfaces-auth's allowlist, so an exhaustive switch over
casestill compiles:basic-encoding-missing:clientSecretBasicwithoutencoding.unsupported-sso-flow:SsoProviderFactory.createswitches exhaustively over its typedflow.required-fields-missingfor a field its type requires:renewal(every token provider,inBrowser,fromTerminal,toConsole,SsoProviderFactory.create);servicePrincipalandtokenSource(SpnegoAuthProvider);presentation,transport,protocolandendpoint(composeAuthorization);presentation(openInBrowserwithoutbrowser);show(consumerPresentation);receive(consumerAnswer);provide(consumerHandoff);redirectUri(manualPasteStrategy,manualSamlResponseStrategy,externalCodeStrategy);assertionValidator(both SAML providers);replayStore(the shipped validators); an absentuaaUrlorclientId(ClientCredentialsProvider,AuthorizationCodeProvider); anSncLogonProvidermyNamethat is not a string. An emptyuaaUrlorclientIdis still refused.invalid-valuefor a value of the wrong type: apersistencewithout a callablereport;refreshStatePersistence'swritenot a function oronWriteFailurenot'continue'/'fail'; a part of an authorization strategy without its methods, a transportlabelor a protocolredirectoff its union; a browser name where anIBrowserbelongs;remoteHintorreadnot a function;showforconsumerPresentation'sonFailurenot a function; aservicePrincipalorredirectUrithat is not a string. A string that cannot be used is still refused.snc-partner-name-missingfor apartnerNamethat is not a string,validator-no-certificatesforidpCertificatesabsent or not an array,idp-certificate-invalidfor a certificate that is not a string. An empty or blankpartnerName, an emptyidpCertificatesand a malformed certificate are still refused.
- An answer typed
voidis ignored. A request target'sheader()/cookies(), everyILoggermethod and the renewal strategy'saborted()are typedvoid; 7.x adopted what they returned and contained a rejection. A throw from the call is still handled. A rejecting promise returned despite thevoidtype now raisesunhandledRejectionin your process: return nothing, or handle your own promise. - A collaborator's answer is used as typed. It is still adopted as
awaitadopts it (a thenable works), then used as its contract types it. A throw while it is read — a getter of the answer — is handled like a throw from the call. An answer of another shape is no longer refused for its shape (a renewal decision with an unknownnext, say); what follows is not stated.
Migrating to 6.0.0 — the error contract
6.0.0 replaces how this package says what went wrong. Every refusal and every
throw is now an error of one closed list of kinds, minted by
@mcp-abap-adt/auth-errors
from allowlisted facts — not a class to match with instanceof, not words to
parse. And nothing is bounded by a timeout of the package's choosing any more:
your AbortSignal is the bound. What a consumer on 5.x must now do:
Install the contract it is read with.
@mcp-abap-adt/auth-errors(^2.2.0) to read errors;@mcp-abap-adt/interfaces-auth(^7.5.0) is what every provider here implements, and where the parts of an authorization strategy (IAuthorizationPresentation,IAnswerTransport,IAuthorizationProtocol,IBrowser) are declared. The consumers on the same contract are published:@mcp-abap-adt/connection15.0.0,@mcp-abap-adt/auth-stores5.0.1,@mcp-abap-adt/auth-broker5.0.5 and@mcp-abap-adt/auth-broker-cli3.1.1. An older connection does not read these providers' refusals: 11.x reads the old refusal, and 12.0.0 (published only undernext) is built on interfaces-auth 6. Keep one copy of each:npm ls @mcp-abap-adt/interfaces-authandnpm ls @mcp-abap-adt/auth-errorsshould show one deduplicated version.Every token provider requires
renewal. How a renewal proceeds — whether to refresh, whether to log in, when to stop, what becomes of a refresh token that was sent — is now a strategy the consumer gives (renewal: IRenewalStrategy). There is no default: a token provider (andinBrowser,fromTerminal,toConsole,SsoProviderFactory.create) constructed without one, or with one whosenextis not a function, throwsconfigurationrequired-fields-missingwithfields: ['renewal'](until 8.0.0: see Migrating to 8.0.0).renewal: refreshThenLogin()takes the steps 5.x took — one refresh, then one login when there is no refresh token or the refresh failed;refreshOnly()never logs in. See Renewal strategy.import { ClientCredentialsProvider, refreshThenLogin } from '@mcp-abap-adt/auth-providers'; const provider = new ClientCredentialsProvider({ uaaUrl, clientId, clientSecret, renewal: refreshThenLogin(), });onTokensis gone; passpersistence. The config fieldonTokensis replaced bypersistence?: ITokenPersistence, which receives one report per change of the provider's credentials (see Persistence strategy). The 5.x behaviour ofonTokens— called with every new token, best effort — isrefreshStatePersistence(write, { onWriteFailure: 'continue' }):// 5.x onTokens: async (result) => save(result), // 6.0.0 persistence: refreshStatePersistence( async ({ authorizationToken, refreshToken, expiresAt }) => save({ authorizationToken, refreshToken, expiresAt }), { onWriteFailure: 'continue' }, ),write'srefreshTokenis a string (a new one: write it),undefined(the result carried none: leave the stored one, as a 5.xonTokensresult without a refresh token meant) ornull— new — (the provider discarded the refresh token: clear the stored one, so it is never sent again after a restart).onWriteFailureis required, with no default:'continue'logs a failed write and goes on, asonTokensfailures did;'fail'makes the call that caused the write fail with it. A persistence strategy of your own whose awaited report throws now fails that call (getTokens(),refreshTokens(), or the moment) —unknown, operationpersisting-tokens— where 5.x only logged a failingonTokens; the credentials stay committed and the nextgetTokens()answers them. Withoutpersistencenothing is persisted.No
refreshTokenDisposition. interfaces-auth 6.0.0 added it toITokenResult; interfaces-auth 7 removed it again, with the typeRefreshTokenDisposition, and no release of this package carries it. WhatgetTokens()/refreshTokens()return carries the refresh token the provider holds, orrefreshToken: undefined— nothing more. A store learns what became of the refresh token from the persistence reports.What a renewal answers changed where it could not produce a usable credential — it now throws, and what follows (log in again, give up) is yours. With
refreshThenLogin():- a renewal that obtains a token still bound to another certificate than
the pinned one:
getTokens()/refreshTokens()throwtoken-bindingrenewed-bound-elsewhere(5.x returned the token); - a held token remembered as bound elsewhere:
getTokens()throws the remembered error (5.x returned the token);prepare()no longer clears what is remembered — it renews once more; rejected()with a401whose renewal is still bound elsewhere: Oopsrenewed-bound-elsewhere(5.x answered Ok);- a remembered expired client certificate is refused again by the pin — an equal refusal, no longer the same object;
- a result that carries no usable refresh token — a refresh answered without a new one, a login without one — leaves the refresh token held in place (5.x dropped it), so the next renewal can still refresh;
- a
403for a token a renewal has already replaced: Ok, since what is presented changed; - a refresh that failed before it was sent (discovery, a client-authentication strategy or a loader failed first) no longer discards the refresh token.
- a renewal that obtains a token still bound to another certificate than
the pinned one:
A new kind,
renewal-declined— "the renewal strategy declined to renew the credential",facts.trigger— for a renewal strategy that stops before taking any step, with no other refusal that explains it (for instancerefreshOnly()with an expired token and no refresh token). An exhaustivematchKind/unreachableKindmust handle it.invalid-valueis a configuration case, "a configured value cannot be used:<fields>": an unparseableauthorizationUrl(5.xrequired-fields-missing), apersistencewithout a callablereport,refreshStatePersistence'sonWriteFailureorwrite, a part of an authorization strategy that cannot be used (below). Since 8.0.0 a value of the wrong type is not refused: see Migrating to 8.0.0.Catch with
readFailure, neverinstanceof. Every throw of this package — a constructor's configuration fault, a factory's, a loader's,getTokens()/refreshTokens()— is anAuthProviderFailure(one exception, your own error:refreshStatePersistence'sreport(), below). Read what you caught withreadFailure(thrown, operation), which answers anIAuthProviderErrorfor anything (a failure of another installed copy of auth-errors included, a forged one rebuilt from its kind and facts); test withisAuthProviderFailure(value)when you need a yes/no. Aninstanceofanswers false across two copies of the package and true for a forgery, so it is never the test.import { matchKind, readFailure } from '@mcp-abap-adt/auth-errors'; try { await provider.getTokens({ signal }); } catch (thrown) { const error = readFailure(thrown, 'token-request'); const advice = matchKind(error, { configuration: (e) => `fix ${e.facts.fields.join(', ')}`, 'interactive-login': (e) => (e.facts.outcome === 'aborted' ? 'cancelled' : e.reason), 'request-failed': (e) => `${e.reason}${e.facts.oauthError ? ` [${e.facts.oauthError}]` : ''}`, // … every kind: a missing handler does not compile … unknown: (e) => e.reason, }); }Switch on
kindwith one of auth-errors' two exhaustiveness patterns —matchKind(error, handlers), or aswitchwhosedefaultcallsunreachableKind(error)— so that a kind added by a later major stops your build instead of falling through at run time. A plainswitchis not checked.The classes are gone.
TokenProviderError,ValidationError,RefreshError,SessionDataError,ServiceKeyError,BrowserAuthError,AssertionValidationError,CertificateMaterialError,ClientAuthenticationError,ClientAuthenticationResultError,BasicClientIdErrorandTokenEndpointErrorare no longer exported, andAssertionCheckis imported from@mcp-abap-adt/interfaces-auth. What each carried is a kind and its facts:| 5.x | 6.0.0 | |---|---| |
ValidationError(missingFields) |configuration—facts.case,facts.fields(Configuration errors) | |BrowserAuthError|interactive-login—facts.outcome(aborted,port-in-use,identity-provider-refused,busy,disposed,no-terminal, …) | |TokenEndpointError(status,oauthError,code); the reducedAxiosError|request-failed—facts.operation,facts.problem,facts.status,facts.oauthError,facts.code;tls—facts.code| |AssertionValidationError(check) |saml-assertion—facts.rule,facts.check(Refusal messages) | |CertificateMaterialError(incomplete,expired) |client-certificate—facts.problem(incomplete,unusable,expired) | |ClientAuthenticationError,ClientAuthenticationResultError,BasicClientIdError|client-authentication—facts.problem(signing-key-unusable,result-unsendable,basic-client-id-colon) | |RefreshError|credential-refusedrefresh-token— withrefreshThenLogin(), as before, a refused refresh falls back to one login inside the provider | |SessionDataError,ServiceKeyError| nothing: they had no producer | |error.code(TOKEN_PROVIDER_ERROR_CODES,ASSERTION_ERROR_CODES) |kind— the constants are gone from interfaces-auth 6.0.0 |refusalWords(error, what)→classify(error, operation)(auth-errors), then.reason/.hint.whatwas free text; an operation is one of the closed listOPERATIONSof interfaces-auth ('loading-certificate','token-request', …). A caller that passed awhatof its own and wants no operation's words passes'unfamiliar-error', which answers "an authentication error of a kind this version does not know" and no hint — a TLS failure'sNODE_EXTRA_CA_CERTShint included; an operation of the list keeps its words and hints. See Relaying a refusal.A refusal is frozen, and only a minted one is trusted.
AuthOutcome's refusal is theIAuthProviderErroritself (IAuthRefusal = IAuthProviderError):refusal.reasonandrefusal.hintread as before, andrefusal.kind/refusal.factssay what happened. Do not copy or edit one: it is frozen, so a mutation throws in strict code, and a copy ({ ...refusal }, astructuredClone, a JSON round-trip) is no longer minted — wherever it is read again it is rebuilt from itskindandfacts, its diagnostics dropped; a provider of yours answering an outcome that is not one is answeredunknown. Build an error you need with auth-errors'authErrorbuilders.The words changed; match on facts. Every reason and hint is rendered from the kind and its facts. A token request refused reads
the passcode exchange failed (HTTP 401)instead ofPasscode exchange failed (401); an unfamiliar thrown valueloading the certificate failed (unknown error, ENOENT)instead of naming a class or yourwhat; a SAML refusal names its rule and no value of the document; the SNC library's path is a diagnostic, not a word. Code that matched words must matchkindandfactsinstead.No
timeoutMsanywhere.DEFAULT_LOGIN_TIMEOUT_MS, every strategy'stimeoutMs, the factories'{ timeoutMs }and the 30 s (browser) and 300 s (passcode) defaults are removed, and so are the client credentials request's 30 s timeout and the SNC registry query's 5 s. A consumer passingtimeoutMsmust passsignal: AbortSignal.timeout(ms)instead — to the strategy, or toinBrowser/fromTerminalas{ signal }; one passing nothing now waits until it aborts — a login until its result or the identity provider's refusal, a request until the server or the OS ends it. See Cancelling a login.A browser that does not open is no longer an error. A browser that throws or rejects (yours, or a shipped one) gets one log line in fixed words and the authorization URL as a prompt on stderr, and the login keeps waiting: the callback still listens, so the URL shown — the only way to finish where no browser can be opened (SSH, a host without a desktop) — is live. The
browser-launch-failedoutcome is gone, and a launch failure never ends the login; code that matched it must stop. Bound the login with asignal(AbortSignal.timeout(ms)), or it ends on its result, the identity provider's refusal or your abort.A login is bound to its attempt (login CSRF). Every URL
AuthorizationCodeProviderandOidcBrowserProviderbuild carriesstate(and, for UAA, a PKCE challenge, S256); a configuredauthorizationUrlwithoutstategets the provider's, which the identity provider must echo. The shipped protocols accept a redirect — a code or an?error=— only with thatstate; a consumer's own strategy that receives the redirect itself must checkstateitself. The shipped listeners bind loopback only, and answer onlyHost: localhost/127.0.0.1/[::1]with their port, from a loopback peer: a browser on another machine reaches them through an SSH tunnel, or through a transport of your own. The paste page's/submitneeds the form's token. See Login CSRF:state, PKCE and where the callback listens, and Interactive login: strategies by composition below for what changed in the strategies.Your strategies end on the request's signal. Every
AuthorizationRequestcarriessignal.externalCodeStrategy'sprovideis(authorizationUrl, signal), and a manual strategy'sread(prompt, signal)must settle when its signal aborts: one that ignores it now blocks that strategy'sauthorize— and the next login, which waits for the aborted one to settle — where 5.x settled through a race.The server's text is gone, also from logs. A token endpoint's
error_descriptionanderror_uriare read by nothing, in errors and in log lines, by default and withauthDebug; only a registered OAutherrorsurvives, asfacts.oauthError(5.4.2'serr.response.data.error). A consumer that readerror_descriptionfrom a log or an error no longer finds it.authDebug: trueon a token provider adds, to its one line for a failed request, the secrets the request sent — each prepared: at most its first 4 and last 4 characters plus its length, the length only below 16 characters — and never the server's text. See Debug Logging.A subclass of
BaseTokenProvider.performLogin()is nowperformLogin(attempt)— handattempt.signalto whatever the login waits on — andperformRefresh()isperformRefresh(refreshToken, signal, dispatched): send the refresh token you are given — readingthis.refreshTokeninstead may send one the renewal strategy discarded, a spent one — and calldispatched()right before the request leaves (passthis.refreshSiteOptions(dispatched)to a shipped token site, which does it). A refresh that never callsdispatched()counts as never sent: an abort then never applies the decision'sifCut, and its refresh token stays held although the server may have spent it. A subclass's constructor passesrenewalthrough its config like any other token provider. A provider of your own extendsAuthProviderBaseand implementsonPrepare(),onEstablish(logon),onAuthorize(request)andonRejected(rejection); the base owns the four moments and runs each inside auth-errors'guard. See Writing a provider of your own.A cut refresh: the strategy decided before it was sent. A refresh whose callers all aborted after it was sent runs on; what becomes of the refresh token it sent is the
ifCutof the decision that started it.refreshThenLogin()andrefreshOnly()say'discard'— that refresh token is never sent again by the provider, so withrefreshThenLogin()the next renewal may log in, as in 5.x; a strategy of your own may say'keep'. A refresh aborted before it was sent touches no refresh token. See Cancelling a login.A declined SAML login is refused
declined. The signed-Response validator readsStatusright after the signature checks, before counting theAssertion, so a login the identity provider declined — which carries no Assertion — is refuseddeclinedwith its status code, where 5.x refused it as carrying no direct-child Assertion (no-direct-assertion).Device polling follows RFC 8628.
slow_downadds 5 s to every later poll, cumulatively; anintervalthat is not a finite, non-negative number is 5 s;authorization_pending/slow_downkeep the poll going only with status400.
What is no longer available anywhere (each decided with the change; the facts that remain are listed with it):
- the token endpoint's
error_descriptionanderror_uri(the registerederrorstays, asfacts.oauthError); - a
causeon any error, and the identity of a thrown value: a strategy's, loader's or presenter's own error reaches you classified, never as itself, and noAxiosErrorescapes; - a rejected configuration value — the callback
port, the SNCqop, aclockSkewMs(the field name stays, and forqopthe allowed values); - each configuration error's own sentence, replaced by its case's fixed words;
- the text of an exception inside a SAML refusal (xml-crypto's, the XML parser's);
- a document value that fails admission (a control, bidirectional or line-separator character, or the wrong shape) — dropped, not escaped;
- values moved from the words to
diagnostics— the SNC library path, each SNC candidate's path, the two URIs of an ACS or redirect mismatch: shown byrenderDiagnostics(error), not byreason/hint; - your own
whatin a relayed refusal (an operation of the closed list instead); - the class label in "
<what>failed (<Class>)", and which of the abort moments or empty inputs a login met; error.code,missingFields,checkas a property,CertificateMaterialError.incomplete/.expired/.words,TokenEndpointError.status/.oauthError/.code— each now a fact;- the diagnostics of an error that crosses another installed copy of auth-errors, or that was not minted (its kind and facts stay);
- every built-in login timeout and its message ("Authentication timeout after N seconds", "did not arrive in time");
- the authorization URL in a log line: it is prompted on stderr only, and the logger gets "the authorization URL was shown";
- the log lines of 5.x's
'auto'browser, and theDISPLAY=:05.x set for'system'and a named browser: a browser has no logger, and the package writes nothing intoprocess.env; - the
openandexpressdependencies.
Interactive login: strategies by composition
An authorization strategy is now composed of three parts, each a
contract of @mcp-abap-adt/interfaces-auth 7.4.0 (IBrowser is 7.5.0's): a presentation (how
the URL reaches the user), a transport (how the user's answer comes
back) and a protocol (what an answer is and how it is checked). The
named strategies are compositions of the shipped parts, under the same
names (see Composing a strategy from parts).
What a consumer on 5.x must now do:
browserCallbackStrategy/oidcCallbackStrategy/samlCallbackStrategywithport,signal,remoteHint: no change.browseris anIBrowser, no longer a string — no browser is named by a string anywhere — and you pick it for the platform you run on:| 5.x | Linux | macOS | Windows | |---|---|---|---| |
'system','auto'|linuxDefaultBrowser()|macDefaultBrowser()|windowsDefaultBrowser()| |'chrome'|linuxBrowser('google-chrome')|macBrowser('Google Chrome')|windowsBrowser('chrome')| |'edge'|linuxBrowser('microsoft-edge')|macBrowser('Microsoft Edge')|windowsBrowser('msedge')| |'firefox'|linuxBrowser('firefox')|macBrowser('Firefox')|windowsBrowser('firefox')| | any other name ('msedge'included) — 5.x opened the system default browser |linuxDefaultBrowser()|macDefaultBrowser()|windowsDefaultBrowser()| |'none','headless', absent | nobrowser| nobrowser| nobrowser|// 5.x: browserCallbackStrategy({ browser: 'system' }) browserCallbackStrategy({ browser: linuxDefaultBrowser() })There is no platform check: each factory runs exactly its program, and on another OS it does whatever a program of that name does there — see The six shipped browsers. Pick the one for your platform. A consumer whose configuration holds a browser name maps it itself.
No list of candidates. 5.x handed a named browser to the
openpackage, which on Linux took the first ofgoogle-chrome,google-chrome-stable,chromium,chromium-browser(for'chrome') ormicrosoft-edge,microsoft-edge-dev(for'edge') that was installed, andfirefoxfor'firefox'; only whenopencould not be loaded did a shell fallback try its own list. Now pass the executable that is installed —linuxBrowser('google-chrome-stable'),linuxBrowser('chromium'),linuxBrowser('/usr/bin/firefox-esr')— a name onPATHor an absolute path, as given.'auto'and'system'are one: the platform's default browser. The log lines 5.x's'auto'wrote while it tried launchers are gone (anIBrowserhas no logger); a browser that fails shows only as the composer's fixed-words lineFailed to present the authorization URL: …and the URL prompted on stderr.No
DISPLAY=:0. 5.x setDISPLAY=:0on Linux, for'system'and a named browser, when neitherDISPLAYnorWAYLAND_DISPLAYwas set. The package now writes nothing intoprocess.env: without a display the launcher does what it does there (xdg-openfails, or starts a console browser it finds); a launch that fails has the URL shown once on stderr while the login waits. A display of your choice — or a remote Chrome, a console browser, WSL, an ssh-forwarded X — is a browser of your own (A browser of your own).The
openpackage is gone (andexpress): every launch is the package's own, a program started with an argument array, never a shell. A shipped browser binary (linuxBrowser) resolves as soon as it has started; a hand-off launcher (xdg-open,open,rundll32, PowerShell'sStart-Process) when it exits0.openUrlis gone. One hook per decision: a callback that only opened the URL becomes anIBrowser, passed asbrowser; one that needed the redirect URI, or showed the URL in its own UI, becomesconsumerPresentation({ show }), composed withcomposeAuthorization(Where the URL is shown).// 5.x: browserCallbackStrategy({ browser: 'system', openUrl: (url) => myOpen(url) }) browserCallbackStrategy({ browser: { open: (url) => myOpen(url) } })In TypeScript
openUrlno longer compiles. From plain JavaScript it is an unknown key, ignored without a word — so a 5.x JavaScript consumer that usedopenUrlto keep the URL (and thestateit carries) off stderr now gets them on stderr, unless it passes its ownIBrowseror presentation.callbackServeris gone. A receiver of your own is anIAnswerTransport, composed:composeAuthorization({ presentation, transport: myTransport, protocol: oauthCode(), endpoint: '/callback' }). The transport hands each answer to the protocol's judge and never returns a payload: the composer takes only the payload the protocol accepted (A transport of your own). TheBrowserCallbackStrategyclass,BrowserCallbackStrategyOptions,withBrowserCallbackServer,withOidcCallbackServerandwithSamlCallbackServerare removed — usecomposeAuthorizationand the parts.CallbackServerFactory,ICallbackServerOptionsandICallbackServerHandlestay in interfaces-auth 7.4.0, deprecated and implemented by nothing.A listener on another address is your own transport. The shipped listeners bind loopback only and advertise only what they bind. A listener on a network address, a hostname, a wildcard, behind a proxy or a translated port is an
IAnswerTransportof yours, which builds its redirect from its own origin and the endpoint path — or keep the loopback listener and tunnel (ssh -L <port>:localhost:<port> <this machine>; see The SSH tunnel). (ThehostandallowedHostsoptions of the 6.0.0 prereleases never shipped.)The terminal and consumer-code strategies need
redirectUri.manualPasteStrategy(),manualSamlResponseStrategy()andexternalCodeStrategy({ provide })withoutredirectUrithrowconfigurationrequired-fields-missingnamingredirectUri(until 8.0.0, where the type requires it): pass the redirect registered with the identity provider (the ACS for SAML). Theirhttp://localhost:61001/callbackdefault is gone — it reached whatever held port 61001.manualPasscodeStrategy'sredirectUriis gone (it was unused).staticCodeStrategyis unchanged.externalCodeStrategytakes OAuth codes only. A SAML response or a passcode handed over by your code composesconsumerHandoffwithsamlResponse()orpasscode():const { presentation, transport } = consumerHandoff({ redirectUri: acsUrl, provide: (url, signal) => ourSsoProxy.login(url, signal), }); const strategy = composeAuthorization({ presentation, transport, protocol: samlResponse(), endpoint: '/callback', });The paste page's
/submitis aPOST(urlencoded,form_tokenandinput, up to 5 MB), and every listener serves the paste page for its protocol — OIDC and SAML too, which had none. A page of yours thatGETs/submitmustPOST.Overlap is
busy. A secondauthorizeon one strategy while the first runs isinteractive-loginbusy, for every composition — two terminal readers on one stdin are never right.Every redirect callback is closed until the URL exists, the SAML one included; there is no gate to opt out of.
The authorization URL is prompted on stderr only. 5.x wrote the prompt to the logger's
infowhen there was one. The URL carriesstate, and a configured one may carry anything, so it reaches no log line: the logger gets "the authorization URL was shown". Where the callback waits and the SSH hint still go to the logger (stderr without one). A consumer whose stderr is collected into its logs — an MCP server, say — shows the URL in its own UI withconsumerPresentation.A configured
authorizationUrlwithoutstategets one. The provider appends its mintedstateto it, so the identity provider must echo it (RFC 6749 §4.1.2); a URL that already carries onestatekeeps it. No redirect is accepted without this attempt'sstate.A strategy of your own written from scratch (
IAuthorizationStrategy) is unaffected:IAuthorizationStrategyandAuthorizationRequestdid not change.
Migrating to 5.0.0 — a migration, not an update
History: the code and the error classes shown in this section are for that old version (5.0.0) and do not compile on 6.0.0. For 6.0.0, see Migrating to 6.0.0 — the error contract.
This section and the migrations after it describe earlier majors: their code shows the API of the version they migrate to, and the version they migrate from. Coming from one of them, apply them in order and then Migrating to 6.0.0 — above all for
browser, now anIBrowserrather than a name, and for the manual and consumer-code strategies, which now requireredirectUri.
History: what 5.0.0 changed. Where 6.0.0 changed it again — onTokens
(now persistence), the timeoutMs of the manual strategies,
BrowserAuthError, the connection version —
Migrating to 6.0.0 is what holds.
5.0.0 is not an incremental release. Every provider here now implements
IAuthProvider (@mcp-abap-adt/interfaces-auth 3.0.0) and can be handed to
the process with no wrapper and no check of what it is — which is what a
consumer migrates to, building its providers from this package and
handing them to a @mcp-abap-adt/connection 10.0.0 process, rather than
updating in place; 9.x speaks the old, narrower IAuthProvider.
- Credentials come from here, not from
@mcp-abap-adt/connection.BasicAuthProvider,CertificateAuthProvider,SamlAuthProvider,TokenAuthProviderandFileCertificateMaterialLoadermoved into this package (src/credentials/);connection10.0.0 removes its own copies. Import them from@mcp-abap-adt/auth-providersinstead. - A token provider is handed to the process as it is.
BaseTokenProvider implements IRefreshableTokenProvider, IAuthProvider, so every token provider —AuthorizationCodeProvider,ClientCredentialsProvider,OidcBrowserProvider,OidcDeviceFlowProvider,OidcPasswordProvider,OidcTokenExchangeProvider,Saml2BearerProvider,Saml2PureProvider,UaaPasscodeProvider— is anIAuthProvider, with noTokenAuthProviderwrapper around it. The broker's token API (getTokens()/refreshTokens()) is unchanged. - A store that persisted after
getTokens()passesonTokensinstead. Every token provider's config takes an optionalonTokens?: (result: ITokenResult) => Promise<void>, called after every new token — a login or a refresh, never a cache hit — and awaited before the provider answers. It is best effort: a failingonTokensis logged (in fixed words only, since it holds the tokens) and does not fail the authentication. - Nothing is defaulted any more. A provider that used to build its own
strategy, SAML validator, replay store or device-code output now takes it
explicitly in its constructor — or the consumer calls the named factory:
AuthorizationCodeProvider.inBrowser,OidcBrowserProvider.inBrowser,Saml2PureProvider.inBrowser,Saml2BearerProvider.inBrowser,UaaPasscodeProvider.fromTerminal,OidcDeviceFlowProvider.toConsole,CertificateAuthProvider.fromFiles,SncLogonProvider.forSecureLoginClient. Omittingauthorization(or, for the SAML providers,assertionValidator) no longer compiles. - SAML trust configuration moved.
idpCertificates,clockSkewMsandassertionReplayStoreare no longer fields ofSaml2BearerProviderConfig/Saml2PureProviderConfig; both now takeassertionValidator: IAssertionValidatordirectly (still required, together withidpEntityIdfor a shipped validator). Build one yourself withcreateSignedResponseValidator/createSignedAssertionValidator, or callSaml2PureProvider.inBrowser(config, trust)/Saml2BearerProvider.inBrowser(config, trust)with aSamlTrust({ idpCertificates, clockSkewMs?, replayStore? }) — the recipe builds the shipped validator and defaultsreplayStoretodefaultReplayStore. ShippedValidatorOptions.replayStoreis required. A direct call tocreateSignedResponseValidator/createSignedAssertionValidatormust now pass one —defaultReplayStore, or your own.- Manual strategies take
timeoutMsand can be disposed.manualPasteStrategy,manualSamlResponseStrategyandmanualPasscodeStrategyaccepttimeoutMs?: number; on expiry, or whendispose()is called, the pending read is abandoned with aBrowserAuthErrorand the terminalreadlineit opened is closed —dispose()ends every concurrentauthorize(), and resolves once all have settled.readis now(prompt: string, signal: AbortSignal) => Promise<string>— the signal aborts on timeout or dispose, and a customreadthat ignores it still loses the race. - Needs
@mcp-abap-adt/connection10.0.0.
Passwordless RFC logon (SNC)
SncLogonProvider logs an on-premise system on over RfcTransport with no
password, through an installed SNC product — typically the SAP Secure Login
Client, holding a certificate from SAP Secure Login Service or Kerberos.
Measured 2026-09-29 against an on-premise system (Windows, Secure Login
Client 3.0.3): the SNC logon, discovery, reads and LOCK/UNLOCK all succeeded
over RfcTransport, each RFC conversation its own SNC logon at roughly
1–1.5 s. See docs/passwordless-sso.md for the
HTTP alternatives, which remain undecided.
Prerequisites: the SNC product is installed and can log on to the profile
used for SAP applications (it need not be running beforehand — see the probe
rule below); the ABAP system accepts SNC for RFC and maps the
certificate's SNC name to a user; and, for the RfcTransport wire itself, the
machine has the SAP NW RFC SDK and @mcp-abap-adt/sap-rfc-lite installed.
This package itself depends on neither — it produces logon parameters and
loads nothing.
The usual choice:
import { SncLogonProvider } from '@mcp-abap-adt/auth-providers';
const provider = SncLogonProvider.forSecureLoginClient({
partnerName: 'p:CN=<system SNC name>', // the ABAP system's SNC name
});forSecureLoginClient assembles nodeSncSystem() (the machine seam),
DefaultSncLibraryLocator(system, sncLib) and [SecureLoginClientProbe(system)]
— "this machine, library discovery, the Secure Login Client probe". qop
defaults to '9' (maximum, one of '1' | '2' | '3' | '8' | '9'), and
myName is sent only when set. An empty or blank partnerName or another qop is
thrown by the constructor as an AuthProviderFailure of kind configuration
(snc-partner-name-missing, snc-qop-invalid — see the configuration errors
table); the rejected qop value is never echoed.
No timeout of its own. prepare() may wait on the machine: on Windows the
locator and the Secure Login Client probe read the registry through
reg.exe (by its absolute path under %SystemRoot%\System32, no shell).
Since 6.0.0 that query has no built-in timeout — it runs until reg.exe
answers, or until the provider's signal aborts, which kills the child. Pass
signal (in the config, or to forSecureLoginClient) or attach(signal)
for each party sharing the provider; prepare() then ends Oops aborted
(interactive-login) once every attached party has aborted. With no signal
it waits for reg.exe; bounding it is the consumer's decision
(AbortSignal.timeout(ms)). A locator or probe of your own receives the same
signal as locate(signal) / appliesTo(path, signal). The abort is tested
with a real child process on a POSIX system, and measured on a Windows host
(2026-10-07, Windows 11 x64): the library found through the real reg.exe
(HKLM\Software\SAP\SecureLogin, InstallPath64), and an abort answering
aborted with the reg.exe child ended and none left running. Localised
reg.exe output is not measured.
The explicit assembly, for a different SNC product, or a locator/probe of your own (no implicit defaults — a constructor takes every collaborator):
import {
SncLogonProvider,
DefaultSncLibraryLocator,
SecureLoginClientProbe,
nodeSncSystem,
} from '@mcp-abap-adt/auth-providers';
const system = nodeSncSystem();
const provider = new SncLogonProvider({
partnerName: 'p:CN=<system SNC name>',
locator: new DefaultSncLibraryLocator(system /*, sncLib */),
probes: [new SecureLoginClientProbe(system)], // [] to name no product
});Discovery order and skip rule. With no explicit sncLib,
DefaultSncLibraryLocator tries, in order: the environment variable
SNC_LIB_64 (on a 64-bit process), SNC_LIB, the Windows registry
HKLM\Software\SAP\SecureLogin\InstallPath64 (InstallPath32 on a 32-bit
process) plus lib\sapcrypto.dll, then the macOS bundle /Applications/Secure
Login Client.app/Contents/MacOS/lib/libsapcrypto.dylib. An unusable
candidate — missing, not a recognised library, or built for the wrong
architecture — is skipped, its reason kept, rather than failing the whole
search; empty or whitespace environment variables count as unset, and the
registry value is trimmed before it becomes a path. Nothing usable →
prepare() is Oops, kind snc, variant library-not-found, listing every
candidate tried by its source and its reason, e.g. "no usable SNC library was
found: SNC_LIB (wrong architecture); registry (missing)" — the source is one
of SNC_LIB_64, SNC_LIB, registry, macOS bundle, and the reason one of
missing, not a library, wrong architecture. Since 6.0.0 the paths are
not in the words (they are local values, kept apart so a logger can drop
them): error.facts.candidates[i] holds each source, reason and — for a wrong
architecture — the architectures the file was built for, facts.processArch
this process's, and error.diagnostics.candidatePaths[i] the path tried,
index for index (null for a path the admission check refused, e.g. one
holding a control character). renderDiagnostics(error) prints them as
candidates: SNC_LIB "C:\\…\\sapcrypto.dll" (wrong architecture); registry
"C:\\…\\sapcrypto.dll" (missing). No error message is ever part of it, and it
needs no logger. An explicit sncLib is the only candidate: unusable,
and the Oops names that one — "no usable SNC library was found: sncLib
(missing)", the path in diagnostics — with no fallback to automatic
discovery. With no candidate at all: "no usable SNC library was found: no
candidate (SNC_LIB_64 and SNC_LIB are unset and no Secure Login Client
installation was found)". A locator of your own that throws gets "no usable
SNC library was found" alone: the candidate facts and paths are read only
from DefaultSncLibraryLocator's own failure. The hint is always "set sncLib
to the SNC (GSS) library of your SNC product".
Architecture comes from the
file header — PE Machine; Mach-O thin and universal (FAT_MAGIC /
FAT_MAGIC_64); ELF e_machine — because the trap this guards against is
measured, not theoretical: the Secure Login Client installer sets the
machine-wide SNC_LIB to its x86 library, and a 64-bit Node process needs the
x64 one the registry points at.
The probe rule — the product is named, not checked. A probe
(ISncProductProbe { product; appliesTo(libraryPath) }) only says which
product is behind the library, so that rejected() can say what to do.
SecureLoginClientProbe applies to a library inside the Secure Login
Client's own installation (the registry's install paths on Windows, matched
case-insensitively; the app bundle on macOS); any other SNC library
(gsskrb5.dll, another vendor's) has no product named. prepare() only
resolves the library and notes which probe applies — nothing about the
product is checked before logon, not that it runs, not that a profile is
logged on. prepare() is therefore Ok with the client not running. Measured
2026-09-29 (Windows, Secure Login Client 3.0.3): with the client exited, the
RFC open through its sapcrypto.dll started the client, which logged on —
silently through the identity provider's SSO, or through its logon window. A
"not running" refusal would have stopped logons that succeed. What follows
for a consumer: an RFC open can wait on the client's logon window until
the user answers it. Only the shipped SecureLoginClientProbe (recognised by
class) yields the Secure Login Client hint; a probe of your own names its
product in the log, never in a refusal.
The two explained failures, from rejected() — the RFC SDK reports both
as a generic communication error, so the cause is found by searching the GSS
error text (never returned; only fixed wording and an allowlisted key go out):
A2200019— kindsnc, variantno-credential; reason "the SNC library has no credential to present (A2200019)"; hint "log on in the Secure Login Client, to the profile used for SAP applications" when the Secure Login Client probe applied, otherwise "make sure the SNC product behind the SNC library is logged on" (since 6.0.0 the library's path iserror.diagnostics.library, not a word). Measured 2026-09-29: with the client logged out, closing its logon window failed the RFC open withGSS-API(min): A2200019:Operation aborted by user or application, andrejected()answered with this reason.SNCERR_INIT(or "gssapi library invalid/missing") — variantlibrary-init-failed; reason "the RFC SDK could not initialise the SNC library (<archs>) as its SNC library (SNCERR_INIT)", the path inerror.diagnostics.library, no hint — usually the architecture mismatch above, if a mismatched library somehow reached this point.RFC_LOGON_FAILURE, or a rejection with neither a status nor an RFC key — variantlogon-refused; reason "SNC logon refused", plus the key in parentheses (and asfacts.rfcKey) when there is one — never the underlying message or object.- any other status or allowlisted RFC key (
RFC_CLOSED,RFC_COMMUNICATION_FAILURE, …) — the neutralsystem-refused/rfc-failureof rule 5, not ansncrefusal. Measured 2026-10-07 (Windows 11, Secure Login Client, Kerberos profile): a wrong partner name failed the RFC open withRFC_CLOSEDand no GSS code the provider explains, and so did, once, a logon with the client stopped and no credential to present;rejected()answeredsystem-refused/rfc-failureboth times.
The GSS codes are found by plain substring search, never a regular
expression over the SDK's text. establish() before prepare() is
not-prepared ("the SNC provider is not prepared" — "connect() prepares it
first"); a locator that answers no path is "no usable SNC library was found:
the locator returned no path"; anything else escaping a moment is unknown,
"the SNC provider failed while <moment> (unknown error)". A product probe
that throws is logged ("an SNC product probe failed: the probe failed (unknown
error)") and names nothing; "SNC library not found: <reason>" is logged with
the paths only as the line's diagnostics field.
SPNego (Kerberos) over HTTP
SpnegoAuthProvider sends Authorization: Negotiate <token> on every request,
the token made afresh by a source the consumer composes. It is for HTTP: an
ADT call to an on-premise system that has SPNego enabled (see
docs/passwordless-sso.md). Over RFC the system
refuses a logon with no user, so establish() writes nothing and answers Ok
(rule 3) — hand this provider to a connection that speaks HTTP.
import { SpnegoAuthProvider } from '@mcp-abap-adt/auth-providers';
import { gssapiTokenSource } from '@mcp-abap-adt/auth-spnego-gssapi';
const provider = new SpnegoAuthProvider({
servicePrincipal: '[email protected]', // service@host, the GSS host-based name
tokenSource: gssapiTokenSource({ mechanism: 'spnego' }),
});This package has no native code, no install script and no dependency on
@mcp-abap-adt/auth-spnego-gssapi: the consumer composes the two, and may
give a source of its own instead (INegotiateTokenSource of
@mcp-abap-adt/interfaces-auth 8). No factory assembles the provider with the
system source, and tokenSource has no default (rule 7).
| Option | |
|---|---|
| servicePrincipal | required: the GSS host-based name service@host, nothing else — exactly one @, the service an ASCII letter then letters, digits or -, the host ASCII labels joined by single dots. HTTP/host@REALM (the Kerberos form), whitespace and non-ASCII are configuration invalid-value naming servicePrincipal, never the value, thrown at construction. How the source turns it into its library's form is the source's |
| tokenSource | required: an INegotiateTokenSource, whose token(servicePrincipal, { signal }) is called only inside a moment |
| logger? | an ILogger; a line carries fixed words and logFields of a refusal, never a token or the principal |
| signal? | the first party attached (attach(signal) adds more), as SncLogonProvider: the source is handed a signal that aborts when every attached party has aborted; with none live a moment waits for the source. No timeout of this package's choosing |
The four moments:
| Moment | Does |
|---|---|
| prepare() | asks the source for one token, checks it and drops it: a missing ticket, an unknown principal or an NTLM token fails the connect before any request. Nothing is kept |
| establish() | writes nothing, answers Ok |
| authorize() | asks the source for a new token, checks it, writes Authorization: Negotiate <token> through the target. Never the prepare() token or an earlier request's: a Kerberos authenticator is single-use against a service that checks for replay (measured: the replay cache refuses a token sent twice) |
| rejected() | a 401 is credential-refused kerberos-ticket, with or without a WWW-Authenticate: Negotiate <token> continuation; anything else system-refused (rule 5). The provider does not follow a continuation or retry: the next authorize() brings a fresh token, retrying is the consumer's |
The source answers facts, not errors. INegotiateTokenSource.token()
resolves { ok: true, token } (base64, as it goes after Negotiate ) or
{ ok: false, problem } with a problem of a closed list; the provider mints the
refusal, so no text a source holds can reach one. Its answer is awaited as
await adopts it: a native promise, a promise library's or any thenable, and
read as its type says, narrowed by ok. A source that throws, rejects, or
throws while its answer is read is unknown with the moment's operation. A source's token is checked before it is written: NTLM — raw
(measured: a Windows runner with no domain and no ticket returns a raw NTLM
NEGOTIATE message for spnego; that this is SSPI's fallback is Inference), or
inside a SPNEGO token (Inference: built fixtures only) — is ntlm-token, and a token that is neither Kerberos nor NTLM, or malformed
DER, is token-unreadable; no header is written for either. A source never
caches a token (the contract), and a late answer after every party aborted is
dropped and the moment ends interactive-login aborted (facts.outcome), no header written.
What it refuses — kind spnego, facts.problem and facts.operation
(obtaining-negotiate-token at prepare(), presenting-negotiate-token at
authorize()), no diagnostics. The words are the ones for
obtaining-negotiate-token; at authorize() the operation phrase differs:
| problem | Found by | When | Reason | Hint |
|---|---|---|---|---|
| no-credential | source | no ticket (an expired one: Pending) | obtaining the Negotiate token failed: there is no Kerberos ticket, or it has expired | obtain a ticket: kinit, or the domain logon |
| service-unknown | source | the KDC does not know the service principal | obtaining the Negotiate token failed: the Kerberos server does not know the service principal | check servicePrincipal against the service's registered principal |
| kdc-unreachable | source | no KDC answered (none known for the realm: Pending) | obtaining the Negotiate token failed: no Kerberos server (KDC) answered | check the Kerberos configuration's realm and KDC |
| clock-skew | source | the clock differs from the KDC's beyond its tolerance (Pending) | obtaining the Negotiate token failed: this machine's clock differs from the Kerberos server's beyond its tolerance | check the machine's time |
| binding-unavailable | source | the source's native library could not be loaded | obtaining the Negotiate token failed: the library of the system token source could not be loaded | install the system source's native part |
| source-failed | source | any other failure the source recognises as its own | obtaining the Negotiate token failed: the token source failed | |
| mechanism-unsupported | source | the mechanism asked for is not supported where the source ran | obtaining the Negotiate token failed: the requested mechanism is not supported | check that the system's GSS library supports the mechanism the source was configured with |
| ntlm-token | provider | the token is NTLM, raw or inside a SPNEGO token | obtaining the Negotiate token failed: the token is an NTLM token, not a Kerberos one | the service principal is not known to the domain; NTLM is not used |
| token-unreadable | provider | the token is empty, not base64, or neither Kerberos nor NTLM | obtaining the Negotiate token failed: the token is empty, not base64, or neither a Kerberos nor an NTLM token | |
A 401 is the credential-refused row of
What rejected() answers.
Measured on the Kerberos stand (2026-10-25, MIT krb5 1.20.1 and Apache
mod_auth_gssapi, Testing):
both mechanisms accepted, a fresh token per request, and each refusal above
that a KDC can produce except clock-skew. Against an ABAP system it is
Inference until the second stage: docs/passwordless-sso.md
keeps the tags.
Migrating to 7.0.0
7.0.0 is a major because a new error kind, spnego, exists, and a consumer
that switches exhaustively on kind must handle it. What a consumer on 6.x must do:
- Add the
spnegocase to every exhaustiveswitch (error.kind)/matchKind/unreachableKind— the compiler says where, once the contract packages below are installed. A consumer that never composesSpnegoAuthProvidernever receives it, but its switch must still compile. - Install the contract it is read with:
@mcp-abap-adt/interfaces-auth^8.0.1and@mcp-abap-adt/auth-errors^3.0.1(this package's ranges;@mcp-abap-adt/interfaces-auth-sapis^3.5.0). Keep one copy of each:npm ls @mcp-abap-adt/interfaces-authandnpm ls @mcp-abap-adt/auth-errorsshould show one deduplicated version. - Nothing else changes: no provider, option or refusal of 6.x is changed.
Installation
npm install @mcp-abap-adt/auth-providersOverview
Every provider here is an IAuthProvider (@mcp-abap-adt/interfaces-auth
8) — prepare(), establish(), authorize(), rejected(), each answering
an AuthOutcome and never throwing — handed to the process as it is. An
AuthOutcome is { ok: true } or { ok: false, refusal }, the refusal an
IAuthProviderError minted by @mcp-abap-adt/auth-errors: its kind and
facts say what happened, reason / hint say it in words (see
Error Handling):
import { AuthorizationCodeProvider, refreshThenLogin } from '@mcp-abap-adt/auth-providers';
const provider = AuthorizationCodeProvider.inBrowser({
uaaUrl: 'https://...',
clientId: '...',
clientSecret: '...',
renewal: refreshThenLogin(), // required: how every renewal proceeds
});
// A process of connection 14 or 15
// calls prepare() on connect, authorize() per request, and rejected() on a 401: one renewal through the renewal
// strategy — with refreshThenLogin(), a refresh, else one login.What rejected() answers
A provider blames its credential only when the rejection says the credential
was refused: status 401, or the RFC SDK's RFC_LOGON_FAILURE. Anything else
is answered with a neutral refusal that names only the status or the SDK key.
For a token provider this is a reading its renewal strategy receives
(cause.reading: credential, not-credential, unknown): the shipped
strategies stop on not-credential without a step and answer the neutral
refusal, so nothing is renewed; a strategy of your own may renew anyway (see
Renewal strategy):
| The rejection | Kind | Basic, certificate, SAML cookies, fixed token, SPNego | Token providers, TokenAuthProvider.from |
|---|---|---|---|
| 401, RFC_LOGON_FAILURE | credential-refused | their own refusal: Basic "the user or password was refused"; certificate "the client certificate was refused"; SAML cookies "the SAML session was refused or has expired"; fixed token "the token was refused"; SPNego "the Kerberos ticket was refused" | one renewal; Ok only if the credential changed |
| 403 | system-refused not-authorized | "the credential was accepted, but the user is not authorized (403)" — "check the user's authorizations in the system" | the same, no renewal |
| 3xx, e.g. 302 | system-refused redirected | "the system redirected instead of accepting the credential (302)" — "the service may require another logon procedure (single sign-on, an identity provider)" | the same, no renewal |
| 5xx, e.g. 503 | system-refused system-failed | "the system failed (503), not the credential" — "try again later" | the same, no renewal |
| any other status, e.g. 404 | system-refused other-status | "the system answered 404, which is not a credential refusal" | the same, no renewal |
| another RFC key, e.g. RFC_COMMUNICATION_FAILURE | system-refused rfc-failure | at a logon "the RFC logon failed (RFC_COMMUNICATION_FAILURE), not as a credential refusal"; at a request "the RFC call failed (RFC_COMMUNICATION_FAILURE), not as a credential refusal" | the same, no renewal |
| neither a status nor a known key | system-refused unknown | at a logon "the logon failed (unknown error)"; at a request "the request was refused (unknown error)" | one renewal — the rejection cannot tell |
SncLogonProvider explains a GSS code in the error first (A2200019,
SNCERR_INIT) — the SDK reports SNC logon failures as a communication
failure — and otherwise answers the same way.
The token providers also implement IRefreshableTokenProvider —
ITokenProvider plus refreshTokens() — for the broker's token API:
- ClientCredentialsProvider —
client_credentials, no user interaction - AuthorizationCodeProvider — UAA/XSUAA authorization code, through a browser
- UaaPasscodeProvider — UAA/XSUAA one-time passcode from
/passcode, the logincf login --ssouses: SSO without a browser on this machine - OidcBrowserProvider — OIDC authorization code with PKCE
- OidcDeviceFlowProvider — OAuth 2.0 device authorization grant (RFC 8628)
- OidcPasswordProvider, OidcTokenExchangeProvider — password grant and token exchange (RFC 8693)
- Saml2BearerProvider — a SAML assertion exchanged for an OAuth2 token (RFC 7522)
- Saml2PureProvider — a SAML assertion exchanged for session cookies
Providers are configured via constructor; getTokens() handles refresh/login internally and takes only an optional { signal } — this caller's cancellation (see Cancelling a login). refreshTokens() obtains a new token even while the cached one looks valid — what a caller holding a 401 needs. Either throws only an AuthProviderFailure.
A token is only half of it: whether ADT accepts it depends on the XSUAA client, the trust and the user configured on the SAP side. What each provider needs there, and which are usable for ADT at all, is in docs/btp-setup.md. Logging on without a password — SAP GUI's SNC single sign-on and its HTTP equivalents, X.509 client certificates and SPNego — is in docs/passwordless-sso.md.
Since 2.0.0 an interactive login is conducted by an authorization strategy
(IAuthorizationStrategy from @mcp-abap-adt/interfaces-auth) passed as
authorization. The provider owns what it can compute — the authorization URL
and the token exchange; everything between them (reaching the URL, receiving
what comes back, the port) belongs to the strategy, which a consumer may
replace wholesale. How long to wait is no one's choice but the consumer's:
a login ends on its result, the identity provider's refusal or the consumer's
AbortSignal. See
Choosing an authorization strategy.
Since 5.3.0 a token provider's client may authenticate with a client
certificate or a signed assertion instead of a secret — a strategy passed as
clientAuthentication — and a token bound to that certificate is presented
only together with it. See Client authentication.
Since 4.0.0 both SAML providers validate the assertion before trusting it — its signature, issuer, audience, recipient, time window, the request it answers, and whether it has been seen before — and must therefore be told which identity provider to trust. This is a breaking change: a 3.x SAML configuration fails at construction. See SAML assertion validation.
If you are on an earlier version, see Migrating to 6.0.0, Migrating to 5.0.0, Upgrading from 4.0 to 4.1, Migrating from 3.x to 4.0, Migrating from 2.x to 3.0 and Migrating from 1.x to 2.0.
Responsibilities and Design Principles
The package's parts, boundaries, principles and the decisions behind them are described in docs/architecture.md.
Core Development Principle
Interface-Only Communication: This package follows a fundamental development principle: all interactions with external dependencies happen ONLY through interfaces. The code knows NOTHING beyond what is defined in the interfaces.
This means:
- Does not know about concrete implementation classes from other packages
- Does not know about internal data structures or methods not defined in interfaces
- Does not make assumptions about implementation behavior beyond interface contracts
- Does not access properties or methods not explicitly defined in interfaces
This principle ensures:
- Loose coupling: Providers are decoupled from concrete implementations in other packages
- Flexibility: New implementations can be added without modifying providers
- Testability: Easy to mock dependencies for testing
- Maintainability: Changes to implementations don't affect providers
Package Responsibilities
This package is responsible for:
- Implementing token provider interface: Provides concrete implementations of
ITokenProviderinterface defined in@mcp-abap-adt/interfaces-auth - Token acquisition: Handles OAuth2 flows (browser-based, refresh token, client credentials) to obtain JWT tokens
- Token validation: Validates JWT locally by checking exp claim (no HTTP requests)
- OAuth2 flows: Manages browser-based OAuth2 authorization code flow and refresh token flow
- SAML assertion validation: Verifies a SAML assertion — signature, issuer, audience, recipient, time window, request ID, replay — before either SAML provider uses it
What This Package Does
- Implements ITokenProvider: Provides concrete implementations (
AuthorizationCodeProvider,ClientCredentialsProvider) - Handles OAuth2 flows: Browser-based OAuth2, refresh token, and client credentials grant types
- Obtains tokens: Makes HTTP requests to UAA endpoints to obtain JWT tokens
- Validates tokens: Validates JWT locally by checking exp claim (no HTTP requests)
- Returns tokens: Returns
ITokenResultwithauthorizationTokenand optional `r
