diff --git a/src/main/redux/sagas/auth.ts b/src/main/redux/sagas/auth.ts index 2b55d489a2..4be671ce20 100644 --- a/src/main/redux/sagas/auth.ts +++ b/src/main/redux/sagas/auth.ts @@ -5,14 +5,15 @@ // that can be found in the LICENSE file exposed on Github (readium) in the project repository. // ==LICENSE-END= -import debug_ from "debug"; -import { startExternalAuthentication, matchesExternalAuthenticationCallback, IExternalAuthenticationSession } from "./externalAuthentication"; import { TaJsonDeserialize } from "@r2-lcp-js/serializable"; +import { DOMParser, XMLSerializer, type Document } from "@xmldom/xmldom"; +import debug_ from "debug"; +import { app, AuthenticationResponseDetails, AuthInfo, BrowserWindow, Event as ElectronEvent, Event, HandlerDetails, session, shell, WebContents, WebContentsWillNavigateEventParams } from "electron"; +import { URL_HOST_COMMON, URL_HOST_OPDS_AUTH, URL_OPDS_AUTH_RETRY, URL_PROTOCOL_OPDS, URL_PROTOCOL_OPDS_MEDIA } from "readium-desktop/common/streamerProtocol"; import { logoutOpdsCatalog } from "readium-desktop/main/services/opdsLogout"; import { getFeed } from "./api/opds/feed"; +import { IExternalAuthenticationSession, matchesExternalAuthenticationCallback, startExternalAuthentication } from "./externalAuthentication"; import { submitInlineAuthentication } from "./inlineAuthentication"; -import { URL_PROTOCOL_OPDS_MEDIA, URL_HOST_COMMON, URL_PROTOCOL_OPDS, URL_HOST_OPDS_AUTH, URL_OPDS_AUTH_RETRY } from "readium-desktop/common/streamerProtocol"; -import { BrowserWindow, HandlerDetails, Event as ElectronEvent, WebContentsWillNavigateEventParams, shell } from "electron"; // TypeScript GO: // The current file is a CommonJS module whose imports will produce 'require' calls; @@ -25,6 +26,7 @@ import { BrowserWindow, HandlerDetails, Event as ElectronEvent, WebContentsWillN // @__ts-ignore TS1479 import { Headers } from "node-fetch"; +import { URL } from "node:url"; import { ToastType } from "readium-desktop/common/models/toast"; import { authActions, historyActions, opdsActions, toastActions } from "readium-desktop/common/redux/actions"; import { takeSpawnEvery, takeSpawnEveryChannel } from "readium-desktop/common/redux/sagas/takeSpawnEvery"; @@ -41,28 +43,27 @@ import { httpSetAuthenticationToken, IOpdsAuthenticationToken, wipeAuthenticationTokenStorage, } from "readium-desktop/main/network/http"; -import { ContentType } from "readium-desktop/utils/contentType"; import { + createOpdsPkceTransaction, + exchangeOpdsPkceAuthorizationCode, IOpdsPkceTransaction, OPDS_AUTHORIZATION_CODE_PKCE_TYPE, OPDS_PKCE_CANONICAL_TYPE, - createOpdsPkceTransaction, - exchangeOpdsPkceAuthorizationCode, } from "readium-desktop/main/network/opdsPkce"; +import { ContentType } from "readium-desktop/utils/contentType"; import { tryCatch, tryCatchSync } from "readium-desktop/utils/tryCatch"; // eslint-disable-next-line local-rules/typed-redux-saga-use-typed-effects import { all, call, cancel, delay, join, put, race, spawn } from "redux-saga/effects"; import { call as callTyped, fork as forkTyped, take as takeTyped } from "typed-redux-saga/macro"; -import { URL } from "node:url"; import { OPDSAuthenticationDoc } from "@r2-opds-js/opds/opds2/opds2-authentication-doc"; import { encodeURIComponent_RFC3986 } from "@r2-utils-js/_utils/http/UrlUtils"; -import { getOpdsRequestCustomProtocolEventChannel, getOpdsRequestMediaCustomProtocolEventChannel, TregisterHttpProtocolHandler} from "./getEventChannel"; -import { initClientSecretToken } from "./apiapp"; -import { digestAuthentication } from "readium-desktop/utils/digest"; import isURL from "readium-desktop/common/utils/isURL"; import { _APP_VERSION } from "readium-desktop/preprocessor-directives"; +import { digestAuthentication } from "readium-desktop/utils/digest"; +import { initClientSecretToken } from "./apiapp"; +import { getOpdsRequestCustomProtocolEventChannel, getOpdsRequestMediaCustomProtocolEventChannel, TregisterHttpProtocolHandler } from "./getEventChannel"; // TypeScript GO: // The current file is a CommonJS module whose imports will produce 'require' calls; @@ -80,8 +81,8 @@ import { getTranslator } from "readium-desktop/common/services/translator"; import { SESSION_PARTITION_AUTH } from "readium-desktop/common/sessions"; // https://github.com/cure53/DOMPurify?tab=readme-ov-file#running-dompurify-on-the-server -import { JSDOM } from "jsdom"; import DOMPurify_ from "dompurify"; +import { JSDOM } from "jsdom"; const DOMPurify = DOMPurify_(new JSDOM("").window); const ENABLE_DEV_TOOLS = __TH__IS_DEV__ || __TH__IS_CI__; @@ -945,7 +946,7 @@ async function createOpdsAuthenticationModalWin(urlStr: string, retryWithInterna let urlExternal: string | undefined; let title: string | undefined; - if (/^data:text\/html/.test(urlStr)) { + if (urlStr.startsWith("data:text/html")) { // passthrough } else if (/^https?:\/\//.test(urlStr)) { if (!retryWithInternalBrowserWindowInsteadOfDefaultExternalWebBrowser) { @@ -1145,13 +1146,170 @@ async function createOpdsAuthenticationModalWin(urlStr: string, retryWithInterna // }); // }); - debug("OPDS AUTH win LOAD 1", urlStr.substring(0, 500)); + let _proxyWasBypassed = false; + + let _proxyWasUsernamePassword = false; + let _proxy_username: string | undefined; + let _proxy_password: string | undefined; + let _proxy_url: string | undefined; + + const appOnLogin = ( + event: Event, + _webContents: WebContents | null, + _authenticationResponseDetails: AuthenticationResponseDetails, + authInfo: AuthInfo, + callback: (username?: string, password?: string) => void) => { + + debug("Electron app.onLogin..."); + if (_proxyWasUsernamePassword && authInfo.isProxy && _proxy_username && _proxy_password) { + debug("Electron app.onLogin PROXY"); + event.preventDefault(); + callback(_proxy_username, _proxy_password); + + // try just once (could try several time, but watch out for "Error: ERR_TOO_MANY_RETRIES (-375) loading") + _proxyWasUsernamePassword = false; + _proxy_username = undefined; + _proxy_password = undefined; + _proxy_url = undefined; + app.off("login", appOnLogin); + } + }; + + win.on("close", () => { + debug("OPDS AUTH win close", urlStr.substring(0, 500)); + + if (_proxyWasUsernamePassword) { + debug("OPDS AUTH win close _proxyWasUsernamePassword"); + app.off("login", appOnLogin); + } + _proxyWasUsernamePassword = false; + + if (_proxyWasBypassed) { + debug("OPDS AUTH win close _proxyWasBypassed"); + const authSession = session.fromPartition(SESSION_PARTITION_AUTH, { cache: false }); + authSession.setProxy({ mode: "system" }).then(() => { debug("setProxy ok (system)"); }).catch((eee) => { debug("setProxy nok (system)"); debug(eee); }); + } + _proxyWasBypassed = false; + }); // win.webContents.loadURL - // await DO NOT AWAIT!! (race condition when urlStr is a HTTP link that immediately redirects to OPDS://AUTHORIZE) - win.loadURL(urlStr).then(() => { debug("loadURL() ok " + urlStr); }).catch((err) => { debug("loadURL() nok " + urlStr); debug(err); }); + // DO NOT AWAIT!! (race condition when urlStr is a HTTP link that immediately redirects to OPDS://AUTHORIZE) + + debug("OPDS AUTH win LOAD before 1", urlStr.substring(0, 500)); + win.loadURL(urlStr).then(() => { + debug("loadURL() 1 ok " + urlStr); + }).catch((err) => { + debug("loadURL() 1 nok " + urlStr); + debug(err); + if (err && String(err).includes("(-111)")) { + // Error: (-111) loading + // Chromium + // net::ERR_TUNNEL_CONNECTION_FAILED + + function tryProxy(proxyU: string) { + try { + const parsed = new URL(proxyU); + if (parsed.username || parsed.password) { + _proxy_username = decodeURIComponent(parsed.username); + _proxy_password = decodeURIComponent(parsed.password); + _proxy_url = `${parsed.protocol}//${parsed.host}`; + + _proxyWasUsernamePassword = true; + + debug("_proxy_username: ", _proxy_username); + debug("_proxy_password: ", _proxy_password); + debug("_proxy_url: ", _proxy_url); + + session.defaultSession.setProxy({ + mode: "fixed_servers", + proxyRules: _proxy_url, + }).then(() => { debug("setProxy ok (fixed_servers)"); }).catch((eee) => { debug("setProxy nok (fixed_servers)"); debug(eee); }); + } + } catch (err) { + debug("Proxy URL?", err); + } + } + + let proxyUrl = process.env.HTTPS_PROXY; + if (proxyUrl) { + debug("HTTPS_PROXY ...", proxyUrl); + tryProxy(proxyUrl); + } + if (!_proxyWasUsernamePassword) { + proxyUrl = process.env.HTTP_PROXY; + if (proxyUrl) { + debug("HTTP_PROXY ...", proxyUrl); + tryProxy(proxyUrl); + } + } + if (_proxyWasUsernamePassword) { + app.on("login", appOnLogin); + } - debug("OPDS AUTH win LOAD 2", urlStr.substring(0, 500)); + debug("OPDS AUTH win LOAD before 2", urlStr.substring(0, 500)); + win.loadURL(urlStr).then(() => { + debug("loadURL() 2 ok " + urlStr); + // authSession.setProxy({ mode: "system" }).then(() => { debug("setProxy ok (system)"); }).catch((eee) => { debug("setProxy nok (system)"); debug(eee); }); + }).catch((err) => { + debug("loadURL() 2 nok " + urlStr); + debug(err); + + if (_proxyWasUsernamePassword) { + app.off("login", appOnLogin); + } + _proxyWasUsernamePassword = false; + _proxy_username = undefined; + _proxy_password = undefined; + _proxy_url = undefined; + + if (err && (String(err).includes("(-111)") || String(err).includes("(-375)"))) { + // Error: (-111) loading + // Chromium + // net::ERR_TUNNEL_CONNECTION_FAILED + // + // Error: ERR_TOO_MANY_RETRIES (-375) loading + + _proxyWasBypassed = true; + + const authSession = session.fromPartition(SESSION_PARTITION_AUTH, { cache: false }); + authSession.setProxy({ mode: "direct" }).then(() => { debug("setProxy ok (direct)"); }).catch((eee) => { debug("setProxy nok (direct)"); debug(eee); }); + + debug("OPDS AUTH win LOAD before 3", urlStr.substring(0, 500)); + win.loadURL(urlStr).then(() => { + debug("loadURL() 3 ok " + urlStr); + // authSession.setProxy({ mode: "system" }).then(() => { debug("setProxy ok (system)"); }).catch((eee) => { debug("setProxy nok (system)"); debug(eee); }); + }).catch((err) => { + debug("loadURL() 3 nok " + urlStr); + debug(err); + + _proxyWasBypassed = false; + + authSession.setProxy({ mode: "system" }).then(() => { debug("setProxy ok (system)"); }).catch((eee) => { debug("setProxy nok (system)"); debug(eee); }); + try { + win.close(); + } catch (e) { + debug(e); + } + }); + debug("OPDS AUTH win LOAD after 3", urlStr.substring(0, 500)); + } else { + try { + win.close(); + } catch (e) { + debug(e); + } + } + }); + debug("OPDS AUTH win LOAD after 2", urlStr.substring(0, 500)); + } else { + try { + win.close(); + } catch (e) { + debug(e); + } + } + }); + debug("OPDS AUTH win LOAD after 1", urlStr.substring(0, 500)); if (urlExternal) { setTimeout(() => { @@ -1321,8 +1479,6 @@ const LoginIcon = ` `; -const escapeKeyScript = ""; // ``; // window.close(); - const htmlLoginTemplate = ( urlToSubmit = "", loginLabel = getTranslator().translate("catalog.opds.auth.username"), @@ -1340,16 +1496,29 @@ const htmlLoginTemplate = ( title = getTranslator().translate("catalog.opds.auth.login"); } - return ` + const ID_headTitle = "head-title"; + const ID_h1Title = "h1-title"; + const ID_imgLoginLogo = "img-login-logo"; + const ID_aHelp = "a-help-"; + const ID_aRegisterUrl = "a-register-url"; + const ID_formAction = "form-action"; + const ID_labelForLogin = "label-for-login"; + const ID_labelForPassword = "label-for-password"; + const ID_inputNonce = "inputNonce"; + const ID_inputQop = "inputQop"; + const ID_inputAlgorithm = "inputAlgorithm"; + const ID_inputRealm = "inputRealm"; + + const rawHtmlTemplate = ` - - - - + + + + - ${DOMPurify.sanitize(title)} +