Skip to content

transit ​

@c9up/transit: federated sign-in through an authority the application does not own: OAuth2 and OAuth1 social providers, any OpenID Connect issuer, SAML 2.0 identity providers and LDAP or Active Directory. Guide: Social authentication.

Installation ​

bash
pnpm add @c9up/transit

ream configure @c9up/transit registers the provider, writes config/transit.ts with a Google entry and adds GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET to the environment files. A SAML replay store shared through Redis needs @c9up/quasar.

Entry points ​

ImportContents
@c9up/transitTransitManager, the drivers, defineConfig and the provider factories, the SAML, XML, LDAP and Apple helpers, types
@c9up/transit/configdefineConfig, socials, oidc, saml, ldap and the config types
@c9up/transit/providerTransitProvider (default export)
@c9up/transit/services/mainThe application's TransitManager (default export)
@c9up/transit/configureconfigure(), run by ream configure @c9up/transit
@c9up/transit/testingFakeTransit, a TransitManager that answers sign-ins with declared users

Exports ​

@c9up/transit ​

Manager and configuration:

ExportKindDescription
TransitManagerclassThe configured providers, by name
TransitProviderproviderSame class as @c9up/transit/provider
TransitAppContextinterface{ container, config }, what the provider needs from the application
defineConfigfunctiondefineConfig<T extends TransitConfig>(config: T): T
socialsconstFactories for apple, discord, facebook, github, google, linkedin, linkedinOpenidConnect, spotify, twitter (OAuth1) and twitterX (OAuth2)
oidcfunctionoidc(config: OidcConfig): TransitDriverFactory, any OpenID Connect provider from its issuer
samlfunctionsaml(config: SamlConfig): TransitDriverFactory, a SAML 2.0 identity provider
ldapfunctionldap(config: LdapConfig): TransitDriverFactory, an LDAP or Active Directory directory
TransitConfigtypeRecord<string, TransitProviderEntry>
TransitProviderEntrytypeTransitEntry | TransitDriverFactory
TransitDriverFactorytype() => TransitEntry, built when the manager is

Drivers:

ExportKindDescription
Oauth2DriverclassAbstract base of the OAuth2 drivers; extend it for a custom provider
Oauth1DriverclassAbstract base of the OAuth1 drivers
OidcDriverclassnew OidcDriver(config: OidcConfig): endpoints and keys come from the issuer's discovery document; PKCE and nonce on every redirect
SamlDriverclassnew SamlDriver(config: SamlConfig): redirect binding out, signed response posted back
LdapDirectoryclassnew LdapDirectory(config: LdapConfig), a DirectoryDriver
AppleDriverclassnew AppleDriver(config: AppleConfig), Sign in with Apple over OpenID Connect
GoogleDriver, GitHubDriver, DiscordDriver, FacebookDriver, SpotifyDriver, LinkedInDriver, LinkedInOpenidConnectDriver, TwitterXDriverclassnew …(config: OAuthConfig), OAuth2 providers
TwitterDriverclassnew TwitterDriver(config: OAuthConfig), X over OAuth1; reached through begin()
createCodeVerifierfunctioncreateCodeVerifier(): string, a PKCE verifier (32 random bytes, base64url)
AuthorizeRequestclassWhat a begin() / redirect() customizer edits
AuthorizeCustomizertype(request: AuthorizeRequest) => void
assertOAuthStatefunctionassertOAuthState(state: string | undefined, expectedState: string | undefined): void; throws unless both are present and equal (constant time)
isDirectoryfunctionisDirectory(entry: TransitEntry): entry is DirectoryDriver

Types:

ExportKindDescription
TransitDriverinterfaceA redirect provider: redirectUrl, begin?, callback, userFromToken?
DirectoryDriverinterface{ authenticate(username: string, password: string): Promise<TransitUser> }
TransitEntrytypeTransitDriver | DirectoryDriver
TransitUserinterface{ id, email, name, nickName?, avatarUrl?, emailVerificationState?, raw }
EmailVerificationStatetype'verified' | 'unverified' | 'unsupported'; unsupported when absent
OAuthTokeninterface{ accessToken, refreshToken?, expiresIn?, tokenSecret? }; tokenSecret for OAuth1
RedirectRequestinterface{ url: string; state: string; secret?: string }, what to keep until the callback
OAuthConfiginterface{ clientId, clientSecret, callbackUrl, scopes?, authorizeParams? }
OidcConfiginterfaceOptions of oidc()
SamlConfiginterfaceOptions of saml()
LdapConfiginterfaceOptions of ldap()
AppleConfiginterfaceAppleKey & { callbackUrl; scopes?; authorizeParams? }
OidcMetadatainterfaceThe discovery document fields read: issuer, authorization_endpoint, token_endpoint, jwks_uri, userinfo_endpoint?, …
RemoteOptionsinterface{ ttlMs?, minRefetchMs?, now? }: ttlMs (default 1 hour) is how long the discovery document and the key set are trusted before they are fetched again; minRefetchMs (default 5 minutes) is the shortest interval between two refetches for an unknown key
IdTokenClaimsinterface{ iss, sub, aud, exp, iat?, nonce?, azp?, [claim: string]: unknown }
Jwkinterface{ kty, kid?, alg?, use?, [key: string]: unknown }
SupportedAlgtype'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512' | 'ES256' | 'ES384' | 'ES512'

Apple, SAML, XML and LDAP helpers:

ExportKindDescription
appleClientSecretfunctionappleClientSecret(key: AppleKey, now?: number): string, the ES256 JWT Apple takes as client secret (valid 5 minutes)
parseAppleUserfunctionparseAppleUser(value: unknown): { name: string } | undefined, the name Apple posts on the first sign-in only
AppleKeyinterface{ clientId, teamId, keyId, privateKey }
validateAssertionfunctionvalidateAssertion(assertion: XmlElement, expected: SamlExpectations): SamlIdentity
assertResponseSucceededfunctionassertResponseSucceeded(response: XmlElement): void; throws E_TRANSIT_SAML_REJECTED unless the status is Success
validateResponsefunctionvalidateResponse(response: XmlElement, expected: SamlResponseExpectations): void; checks the response's own Destination, Issuer and InResponseTo
assertionInsidefunctionassertionInside(signed: XmlElement, response: XmlElement): XmlElement, the one assertion of the posted response, when the signed element is that assertion or the response itself
SamlIdentityinterface{ nameId, nameIdFormat, attributes: Record<string, string[]>, assertionId, notOnOrAfter, rememberUntil, sessionIndex }
SamlExpectationsinterface{ issuer, audience, recipient, inResponseTo?, clockSkewSeconds?, now? }
SamlResponseExpectationsinterface{ issuer, destination, inResponseTo?, signed }; signed says the signature covers the response itself
SAML_PROTOCOL_NS, SAML_ASSERTION_NSconstThe SAML 2.0 protocol and assertion namespaces
AssertionReplayStoreinterface{ remember(assertionId: string, expiresAt: number): Promise<boolean> }; false for an assertion already seen
MemoryAssertionReplayStoreclassRemembers assertions in this process
RedisAssertionReplayStoreclassnew RedisAssertionReplayStore(client: ReplayRedisResolver, options?: { prefix?: string }); prefix transit:saml:assertion:
replayStoresconstreplayStores.memory() and replayStores.redis({ connection, prefix? }); connection is a client, a resolver, or a @c9up/quasar connection name
ReplayRedisClientinterface{ set(key, value, ...args): Promise<unknown> }
ReplayRedisResolvertypeReplayRedisClient | (() => ReplayRedisClient | Promise<ReplayRedisClient>)
parseXmlfunctionparseXml(source: string, limits?): XmlElement; refuses a DOCTYPE, entity references other than the predefined and numeric ones, and malformed input with E_TRANSIT_INVALID_XML
canonicalizefunctioncanonicalize(element: XmlElement, options?: CanonicalizeOptions): string, exclusive XML canonicalization
CanonicalizeOptionsinterface{ inclusivePrefixes?, withComments?, omit? }
walkfunctionwalk(element: XmlElement): Generator<XmlElement>
childrenNamedfunctionchildrenNamed(element: XmlElement, namespaceUri: string, local: string): XmlElement[]
findByAttributefunctionfindByAttribute(root: XmlElement, attribute: string, value: string): XmlElement | undefined
textOffunctiontextOf(element: XmlElement): string
resolvePrefixfunctionresolvePrefix(element: XmlElement, prefix: string): string | undefined
XML_NSconst'http://www.w3.org/XML/1998/namespace'
XmlElement, XmlNode, XmlAttribute, XmlNamespaceinterface / typeThe parsed XML tree
LdapConnectionclassnew LdapConnection(options: LdapOptions): connect(), bind(dn, password), search({ base, filter, attributes?, scope?, sizeLimit? }), close()
LdapOptionsinterface{ url, allowInsecure?, timeoutMs?, rejectUnauthorized? }
LdapFiltertype{ equals: [attribute, value] } | { present } | { and } | { or } | { not }
LdapEntryinterface{ dn: string; attributes: Record<string, string[]> }
errorsnamespaceThe package's errors, one class per code, see Errors

TransitManager ​

MemberSignatureDescription
beginbegin(name: string, customize?: AuthorizeCustomizer): Promise<RedirectRequest>
begin(name: string, state?: string, customize?: AuthorizeCustomizer): Promise<RedirectRequest>
Start a sign-in through any redirect provider: mints the state, fetches a request token where needed, returns the secret to keep
redirectredirect(name: string, state?: string, secret?: string, customize?: AuthorizeCustomizer): stringThe redirect URL, for a provider that can build it offline; OpenID Connect, SAML and OAuth1 throw
callbackcallback(name: string, code: string, state?: string, expectedState?: string, secret?: string): Promise<{ user: TransitUser; token: OAuthToken }>Finish a sign-in; throws without expectedState or when state differs
authenticateauthenticate(name: string, username: string, password: string): Promise<TransitUser>Verify a login against a directory
userFromTokenuserFromToken(name: string, accessToken: string, tokenSecret?: string): Promise<TransitUser>Read the profile behind a token already held
useuse(name: string): TransitDriverThe redirect provider under name; throws for a directory or an unknown name
directorydirectory(name: string): DirectoryDriverThe directory under name
registerregister(name: string, driver: TransitEntry): voidAdd a provider
registeredDriversreadonly registeredDrivers: string[]The configured names
ts
const { url, state, secret } = await transit.begin('github', (request) => request.mergeScopes(['repo']))
// keep state and secret in the session, redirect to url; then, on the callback:
const { user } = await transit.callback('github', code, queryState, state, secret)

AuthorizeRequest ​

MemberSignatureDescription
scopesscopes(scopes: string[]): thisAsk for exactly these scopes
mergeScopesmergeScopes(scopes: string[]): thisAsk for these scopes as well
clearScopesclearScopes(): thisAsk for no scope; OpenID Connect still sends openid
transformScopestransformScopes(callback: (scopes: string[]) => string[]): thisTransform the scopes later passed to scopes() and mergeScopes()
paramparam(key: string, value: string | number | boolean): thisAdd or replace an authorize parameter
clearParamclearParam(key: string): thisDrop an authorize parameter
getScopesgetScopes(): string[]Scopes this redirect asks for
getParamsgetParams(): Record<string, string>Parameters set so far

param() and clearParam() throw E_TRANSIT_PROTECTED_PARAMETER for scope, state, nonce, code_challenge, code_challenge_method, client_id, redirect_uri and response_type. A customizer works on OAuth2 and OpenID Connect providers; the others refuse it.

TransitDriver ​

MemberSignatureDescription
redirectUrlredirectUrl(state?: string, secret?: string, customize?: AuthorizeCustomizer): stringThe redirect URL; secret is the PKCE verifier for a provider that requires one
beginbegin?(state?: string, customize?: AuthorizeCustomizer): Promise<RedirectRequest>The redirect URL plus the state and secret to keep
callbackcallback(code: string, state?: string, expectedState?: string, secret?: string): Promise<{ user: TransitUser; token: OAuthToken }>Exchange the code; checks the state round trip
userFromTokenuserFromToken?(accessToken: string, tokenSecret?: string): Promise<TransitUser>The profile behind a held token

A custom OAuth2 driver extends Oauth2Driver and sets provider, authorizeUrl, accessTokenUrl, userInfoUrl, defaultScopes and mapUser(raw); requiresPkce, tokenAuth ('body' or 'basic'), authorizeParams() and userInfoParams() are optional. A custom OAuth1 driver extends Oauth1Driver and sets provider, requestTokenUrl, authorizeUrl, accessTokenUrl, userInfoUrl and mapUser(raw).

@c9up/transit/config ​

ExportKindDescription
defineConfig, socials, oidc, saml, ldapfunction / constSame as in @c9up/transit
TransitConfig, TransitDriverFactory, TransitProviderEntrytypeSame as in @c9up/transit

@c9up/transit/provider ​

ExportKindDescription
defaultproviderTransitProvider: builds a TransitManager from the transit config (calling each factory) and fills @c9up/transit/services/main
TransitAppContextinterface{ container, config }

@c9up/transit/services/main ​

ExportKindDescription
defaultconsttransit: TransitManager, the application's manager once TransitProvider booted; a member read before throws

@c9up/transit/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: adds the Google environment variables, registers @c9up/transit/provider, writes config/transit.ts

@c9up/transit/testing ​

ExportKindDescription
FakeTransitclassA TransitManager that answers with declared users; the state and secret round trips are enforced
FakeIdentityinterfacePartial<TransitUser>, what a test declares
BegunSignIninterface{ name, state, secret, authorize? }
CompletedSignIninterface{ name, user }
MemberSignatureDescription
willReturnwillReturn(name: string, identity?: FakeIdentity, token?: OAuthToken): thisDeclare who comes back from name; missing fields are filled in
willAcceptwillAccept(name: string, username: string, password: string): thisDeclare the credentials a directory accepts; without it any pair is accepted
begunreadonly begun: BegunSignIn[]Every begin(), oldest first
signedInreadonly signedIn: CompletedSignIn[]Every completed sign-in
assertBeganassertBegan(name: string): voidA sign-in through name started
assertSignedInassertSignedIn(name: string): voidA sign-in through name completed
assertNobodySignedInassertNobodySignedIn(): voidNo sign-in completed
lastUserlastUser(): TransitUser | undefinedThe user of the last completed sign-in
resetreset(): voidForget the record, keep the declarations

Configuration ​

config/transit.ts, read under the transit key. Each key is a name of your choice; use(name) and begin(name) take that key.

ts
import { defineConfig, oidc, socials } from '@c9up/transit'
import env from '#start/env'

export default defineConfig({
  google: socials.google({
    clientId: env.get('GOOGLE_CLIENT_ID'),
    clientSecret: env.get('GOOGLE_CLIENT_SECRET'),
    callbackUrl: 'https://acme.test/auth/google/callback',
  }),
  work: oidc({
    issuer: 'https://id.acme.com',
    clientId: env.get('OIDC_CLIENT_ID'),
    clientSecret: env.get('OIDC_CLIENT_SECRET'),
    callbackUrl: 'https://acme.test/auth/work/callback',
  }),
})

OAuthConfig (social providers):

OptionTypeDefaultDescription
clientIdstring—The application's client id at the provider
clientSecretstring—Its secret
callbackUrlstring—Where the provider sends the user back
scopesstring[]per providerGoogle openid email profile, GitHub read:user user:email, Discord identify email, Facebook email, Spotify user-read-email, LinkedIn r_liteprofile r_emailaddress, LinkedIn OpenID Connect openid profile email, X (OAuth2) tweet.read users.read users.email
authorizeParamsRecord<string, string>—Extra authorize URL parameters, applied after the driver's

OidcConfig:

OptionTypeDefaultDescription
issuerstring—The issuer URL, as it appears in the tokens. Must be https; http://localhost is accepted for development
clientIdstring—Client id
clientSecretstring | (() => string | Promise<string>)—Secret, or a function called at each token request
callbackUrlstring—Redirect URI
scopesstring[]['openid', 'profile', 'email']openid is added when missing
authorizeParamsRecord<string, string>—prompt, login_hint, acr_values…
userinfobooleantrueAlso call the userinfo endpoint when advertised
leewaySecondsnumber60Clock drift tolerated on the id token
cacheRemoteOptions—Caching of the discovery document and signing keys. ttlMs is also the longest a key the provider withdrew keeps verifying tokens

SamlConfig:

OptionTypeDefaultDescription
entityIdstring—This application's entity id
callbackUrlstring—This application's ACS URL
issuerstring—The identity provider's entity id
signOnUrlstring—The identity provider's sign-on endpoint
certificatesstring[]—The identity provider's signing certificates, from its metadata
nameIdFormatstring—Name identifier format to ask for
clockSkewSecondsnumber60Clock drift tolerated
replayStoreAssertionReplayStore | (() => AssertionReplayStore)memoryWhere used assertions are remembered; in production one must be set
claims{ email?; name?; nickName? }—Attribute names when not the usual ones
trustEmailbooleanfalseMark every asserted address verified
trustedEmailDomainsstring[]—Domains whose addresses are verified; others are unverified

LdapConfig:

OptionTypeDefaultDescription
urlstring—ldaps://…
baseDnstring—Where to search from
loginAttributestring—uid, sAMAccountName, userPrincipalName…
bindDn, bindPasswordstring—The account the search runs as; omitted, the search is anonymous
filterLdapFilter—Extra conditions, ANDed with the login attribute
attributesstring[]the mapped onesAttributes to read
claims{ email?; name?; nickName? }—Attribute names when not the usual ones
allowInsecurebooleanfalseAllow a plaintext connection
rejectUnauthorizedbooleantrueRefuse a server certificate that does not check out
timeoutMsnumber10000Wait for the connection and for each reply

AppleConfig takes clientId, teamId, keyId, privateKey (the .p8 contents), callbackUrl, scopes (default ['name', 'email']) and authorizeParams.

Container bindings ​

TokenResolves to
TransitManager (class)The manager built from the transit config
'transit'The same TransitManager

'transit' is declared in ContainerBindings.

Errors ​

CodeRaised when
E_TRANSIT_INVALID_XMLA provider answered XML that cannot be parsed or uses a refused construct (a DOCTYPE, an entity reference)
E_TRANSIT_PROTECTED_PARAMETERA customizer set or cleared a parameter the sign-in owns, or scope through param()
E_TRANSIT_NOT_BOOTED@c9up/transit/services/main was read before the provider booted, or before setTransit()
E_TRANSIT_UNKNOWN_PROVIDERNo provider of this name is registered. The message names only the provider asked for
E_TRANSIT_NOT_A_REDIRECT_PROVIDERuse() / begin() named a directory (LDAP); call authenticate()
E_TRANSIT_NOT_A_DIRECTORYdirectory() / authenticate() named a redirect provider; call begin()
E_TRANSIT_BEGIN_UNSUPPORTEDbegin() on a driver that has no begin()
E_TRANSIT_TOKEN_PROFILE_UNSUPPORTEDuserFromToken() on a driver that cannot read a profile from a token
E_TRANSIT_USE_BEGINredirectUrl() on a provider whose redirect needs a round trip (OAuth1, OpenID Connect, SAML); call begin()
E_TRANSIT_NO_AUTHORIZE_PARAMSA customizer was passed to an OAuth1 or SAML sign-in, which has no per-request scopes or parameters
E_TRANSIT_STATE_REQUIREDA callback ran without expectedState
E_OAUTH_STATE_MISMATCHThe callback's state is missing or differs from the stored one (possible CSRF): "Unable to verify re-redirect state"
E_OAUTH_MISSING_CODEThe callback came back without its grant (code, oauth_verifier for OAuth1, SAMLResponse for SAML), as when the user denied access; nothing is sent to the provider
E_TRANSIT_MISSING_SECRETA flow lacks the secret it needs: the secret begin() returned (PKCE verifier, OAuth1 request-token secret), or the token secret an OAuth1 access token signs with
E_TRANSIT_PKCE_REQUIREDA provider that requires PKCE got no code verifier
E_TRANSIT_TOKEN_EXCHANGE_FAILEDThe provider's token endpoint answered an HTTP error
E_TRANSIT_NO_ACCESS_TOKENThe token response carries no access token
E_TRANSIT_PROFILE_REQUEST_FAILEDThe provider's profile or userinfo endpoint answered an HTTP error
E_TRANSIT_INVALID_RESPONSEA provider's response is not JSON, or not a JSON object
E_TRANSIT_NO_EMAILLinkedIn returned no email address; the application needs the r_emailaddress scope
E_TRANSIT_CALLBACK_NOT_CONFIRMEDAn OAuth1 provider did not confirm the callback URL
E_TRANSIT_NO_REQUEST_TOKENAn OAuth1 provider answered without a request token
E_TRANSIT_DISCOVERY_FAILEDOpenID Connect discovery answered an HTTP error
E_TRANSIT_INSECURE_ISSUERAn OpenID Connect issuer is not an https URL (http://localhost excepted); raised when the driver is built
E_TRANSIT_INVALID_DISCOVERYThe discovery document lacks a required field, names another issuer, or gives an endpoint that is not https
E_TRANSIT_JWKS_FAILEDFetching the provider's JWKS failed, or it has no keys array. Keys older than cache.ttlMs are not used in its place
E_TRANSIT_UNKNOWN_SIGNING_KEYThe id_token names a signing key the provider did not publish
E_TRANSIT_UNSUPPORTED_ALGORITHMThe provider declares only id_token algorithms transit refuses (asymmetric signatures are required)
E_TRANSIT_NO_ID_TOKENThe token response carries no id_token; check that the openid scope is granted
E_TRANSIT_INVALID_ID_TOKENThe id_token is refused: malformed, bad signature or algorithm, wrong issuer, audience or nonce, expired
E_TRANSIT_NO_USERINFO_ENDPOINTA profile was asked from a token alone and the provider publishes no userinfo endpoint
E_TRANSIT_USERINFO_MISMATCHThe userinfo response describes another subject than the id_token
E_TRANSIT_SAML_REJECTEDA SAML response or assertion is refused
E_TRANSIT_INVALID_SIGNATUREAn XML signature does not verify, or is not one transit accepts
E_TRANSIT_INVALID_BERAn LDAP message does not encode or decode as BER, or a DN, an attribute or a filter value handed to LdapConnection is not a string
E_TRANSIT_QUASAR_MISSINGA Redis replay store names a quasar connection and @c9up/quasar is not installed, or its provider has not booted
E_TRANSIT_INCOMPLETE_CONNECTIONThe quasar connection lacks a command the replay store issues
E_TRANSIT_FAKE_NOT_DECLAREDFakeTransit was asked for a provider no willReturn() declared
E_TRANSIT_FAKE_ASSERTIONA FakeTransit assertion (assertBegan, assertSignedIn, assertNobodySignedIn) failed
E_TRANSIT_LDAP_ERRORA directory refused or could not be reached; resultCode is the LDAP result code when the directory answered one (49 for invalid credentials, status 400)

Each one is a class of the errors namespace and a @c9up/flare Exception, with status 500 except E_OAUTH_STATE_MISMATCH (400), E_TRANSIT_UNKNOWN_PROVIDER (404), and E_TRANSIT_LDAP_ERROR for invalid credentials, an empty login or password, or one that is not a string (400): branch on error.code or on error instanceof errors.E_*. E_TRANSIT_PROTECTED_PARAMETER carries the refused parameter.

The errors a visitor meets during a sign-in (E_OAUTH_MISSING_CODE, E_OAUTH_STATE_MISMATCH, E_TRANSIT_UNKNOWN_PROVIDER) extend errors.HttpResponseException and render themselves. Each has an identifier (errors.<CODE>, the translation key read through ctx.i18n), getResponseMessage(error, ctx) and handle(error, ctx). handle negotiates with request.accepts: { errors: [{ message }] } for JSON, a JSON:API error object for JSON:API, and otherwise a flash (error, and the message under its code) with a redirect back when the request has a session, or the message as text when it has none.

Migration ​

  • TransitError is gone: test error.code, or error instanceof errors.E_TRANSIT_* with import { errors } from '@c9up/transit'.
  • SamlError becomes errors.E_TRANSIT_SAML_REJECTED; E_TRANSIT_PROTECTED_PARAMETER moves to errors.E_TRANSIT_PROTECTED_PARAMETER.
  • LdapError becomes errors.E_TRANSIT_LDAP_ERROR: its code is now 'E_TRANSIT_LDAP_ERROR', and the LDAP result code moved to resultCode (error.code === 49 becomes error.resultCode === 49).
  • E_TRANSIT_STATE_MISMATCH is now E_OAUTH_STATE_MISMATCH, with the message "Unable to verify re-redirect state".
  • A callback without its code raises E_OAUTH_MISSING_CODE before anything is sent to the provider, where it used to fail as E_TRANSIT_TOKEN_EXCHANGE_FAILED.
  • assertionInside(signed) now takes the posted response too: call assertionInside(signed, response). It answers the response's one direct <Assertion> child, and refuses a signed element that is neither that assertion nor the response.
  • A SAML sign-in now refuses a signature that is not a direct child of the element it references, a signed element that is neither the posted <Response> nor its one <Assertion>, and any SAML element written under a <ds:Signature>. Identity providers do not send these shapes.
  • authenticate() on a directory now refuses a login or a password that is not a string (an array or an object read from a request body) as invalid credentials: E_TRANSIT_LDAP_ERROR, resultCode 49, status 400. Nothing is sent to the directory. An array or an object used to be sent as an empty password.
  • LdapConnection.bind() refuses a password that is not a non-empty string (E_TRANSIT_LDAP_ERROR), and LdapConnection refuses a DN, an attribute or a filter value that is not a string (E_TRANSIT_INVALID_BER). Convert the value to a string before you pass it.
  • The OpenID Connect signing keys are now fetched again once they are older than cache.ttlMs (default 1 hour), where they used to be kept until a token named an unknown key. A key the provider withdrew stops verifying tokens within that time. Lower cache.ttlMs to shorten it. If the keys cannot be fetched then, the sign-in fails with E_TRANSIT_JWKS_FAILED.
  • oidc() now refuses an issuer that is not https with E_TRANSIT_INSECURE_ISSUER, when the driver is built (at boot). http://localhost is still accepted. For a development provider on another host name, reach it as http://localhost (publish its port) or put TLS in front of it.
  • A discovery document that gives an authorization_endpoint, token_endpoint, jwks_uri or userinfo_endpoint that is not https is now refused with E_TRANSIT_INVALID_DISCOVERY.
  • A signed SAML <Response> must now carry a Destination equal to callbackUrl and an <Issuer> equal to issuer. On any response, a Destination, an <Issuer> or an InResponseTo that is present and differs is refused. Check that callbackUrl is exactly the ACS URL registered at the identity provider.

See also ​