| import { md5 } from 'js-md5'; |
| import { |
| getAPIBaseUrl, |
| getNodeAPIBaseUrl, |
| isTauriAppPlatform, |
| isWebAppPlatform, |
| } from '@/services/environment'; |
| import { fetch as tauriFetch } from '@tauri-apps/plugin-http'; |
| import { READEST_OPDS_USER_AGENT } from '@/services/constants'; |
|
|
| const OPDS_PROXY_URL = `${getAPIBaseUrl()}/opds/proxy`; |
| const NODE_OPDS_PROXY_URL = `${getNodeAPIBaseUrl()}/opds/proxy`; |
| |
| |
| |
| const extractCredentialsFromURL = ( |
| url: string, |
| ): { url: string; username?: string; password?: string } => { |
| try { |
| const urlObj = new URL(url); |
| const username = decodeURIComponent(urlObj.username) || undefined; |
| const password = decodeURIComponent(urlObj.password) || undefined; |
|
|
| if (username || password) { |
| urlObj.username = ''; |
| urlObj.password = ''; |
| return { |
| url: urlObj.toString(), |
| username, |
| password, |
| }; |
| } |
| } catch (e) { |
| console.warn('Failed to parse URL:', e); |
| } |
|
|
| return { url }; |
| }; |
|
|
| export const needsProxy = (url: string): boolean => { |
| return isWebAppPlatform() && url.startsWith('http'); |
| }; |
|
|
| const PROXY_OVERRIDES: Record<string, string> = { |
| standardebooks: NODE_OPDS_PROXY_URL, |
| }; |
|
|
| const getProxyBaseUrl = (url: string): string => { |
| for (const [domain, proxyUrl] of Object.entries(PROXY_OVERRIDES)) { |
| if (url.includes(domain)) { |
| return proxyUrl; |
| } |
| } |
| return OPDS_PROXY_URL; |
| }; |
|
|
| |
| |
| |
| export const getProxiedURL = (url: string, auth: string = '', stream = false): string => { |
| if (url.startsWith('http')) { |
| const { url: cleanUrl } = extractCredentialsFromURL(url); |
| const params = new URLSearchParams(); |
| params.append('url', cleanUrl); |
| params.append('stream', `${stream}`); |
| if (auth) { |
| params.append('auth', auth); |
| } |
| const baseUrl = getProxyBaseUrl(url); |
| const proxyUrl = `${baseUrl}?${params.toString()}`; |
| return proxyUrl; |
| } |
| return url; |
| }; |
|
|
| |
| |
| |
| const parseDigestChallenge = (challenge: string): Record<string, string> => { |
| const params: Record<string, string> = {}; |
| const regex = /(\w+)=["']?([^"',]+)["']?/g; |
| let match; |
|
|
| while ((match = regex.exec(challenge)) !== null) { |
| params[match[1]!] = match[2]!; |
| } |
|
|
| return params; |
| }; |
|
|
| |
| |
| |
| const generateDigestResponse = ( |
| username: string, |
| password: string, |
| params: Record<string, string>, |
| method: string, |
| uri: string, |
| nc: string, |
| cnonce: string, |
| ) => { |
| const realm = params['realm']; |
| const nonce = params['nonce']; |
| const qop = params['qop']; |
| const algorithm = params['algorithm']; |
|
|
| let ha1 = md5(`${username}:${realm}:${password}`); |
|
|
| if (algorithm && algorithm.toLowerCase() === 'md5-sess') { |
| ha1 = md5(`${ha1}:${nonce}:${cnonce}`); |
| } |
|
|
| const ha2 = md5(`${method}:${uri}`); |
|
|
| let response: string; |
|
|
| if (qop) { |
| response = md5(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`); |
| } else { |
| response = md5(`${ha1}:${nonce}:${ha2}`); |
| } |
|
|
| return response; |
| }; |
|
|
| |
| |
| |
| export const createDigestAuth = async ( |
| username: string, |
| password: string, |
| wwwAuthenticate: string, |
| method: string, |
| uri: string, |
| ): Promise<string> => { |
| const params = parseDigestChallenge(wwwAuthenticate); |
| const cnonce = Math.random().toString(36).slice(2); |
| const nc = '00000001'; |
| const response = await generateDigestResponse( |
| username, |
| password, |
| params, |
| method, |
| uri, |
| nc, |
| cnonce, |
| ); |
|
|
| const parts = [ |
| `username="${username}"`, |
| `realm="${params['realm']}"`, |
| `nonce="${params['nonce']}"`, |
| `uri="${uri}"`, |
| `response="${response}"`, |
| ]; |
|
|
| if (params['algorithm']) { |
| parts.push(`algorithm="${params['algorithm']}"`); |
| } |
|
|
| if (params['opaque']) { |
| parts.push(`opaque="${params['opaque']}"`); |
| } |
|
|
| if (params['qop']) { |
| parts.push(`qop="auth"`); |
| parts.push(`nc=${nc}`); |
| parts.push(`cnonce="${cnonce}"`); |
| } |
|
|
| return `Digest ${parts.join(', ')}`; |
| }; |
|
|
| |
| |
| |
| export const createBasicAuth = (username: string, password: string): string => { |
| const credentials = btoa(`${username}:${password}`); |
| return `Basic ${credentials}`; |
| }; |
|
|
| |
| |
| |
| |
| export const probeAuth = async ( |
| url: string, |
| username?: string, |
| password?: string, |
| useProxy = false, |
| ): Promise<string | null> => { |
| const { |
| url: cleanUrl, |
| username: urlUsername, |
| password: urlPassword, |
| } = extractCredentialsFromURL(url); |
|
|
| const finalUsername = username || urlUsername; |
| const finalPassword = password || urlPassword; |
|
|
| |
| if (!finalUsername || !finalPassword) { |
| return null; |
| } |
|
|
| const fetchURL = useProxy ? getProxiedURL(cleanUrl) : cleanUrl; |
| const headers: Record<string, string> = { |
| 'User-Agent': READEST_OPDS_USER_AGENT, |
| Accept: 'application/atom+xml, application/xml, text/xml, */*', |
| }; |
|
|
| |
| const fetch = isTauriAppPlatform() ? tauriFetch : window.fetch; |
| const res = await fetch(fetchURL, { |
| method: 'HEAD', |
| headers, |
| danger: { acceptInvalidCerts: true, acceptInvalidHostnames: true }, |
| }); |
|
|
| |
| if (res.status === 401 || res.status === 403) { |
| const wwwAuthenticate = res.headers.get('WWW-Authenticate'); |
| if (wwwAuthenticate) { |
| if (wwwAuthenticate.toLowerCase().startsWith('digest')) { |
| const urlObj = new URL(cleanUrl); |
| return await createDigestAuth( |
| finalUsername, |
| finalPassword, |
| wwwAuthenticate, |
| 'GET', |
| urlObj.pathname + urlObj.search, |
| ); |
| } else if (wwwAuthenticate.toLowerCase().startsWith('basic')) { |
| return createBasicAuth(finalUsername, finalPassword); |
| } |
| } else { |
| |
| |
| return createBasicAuth(finalUsername, finalPassword); |
| } |
| } |
|
|
| |
| return createBasicAuth(finalUsername, finalPassword); |
| }; |
|
|
| export const probeFilename = async (headers: Record<string, string>) => { |
| const contentDisposition = headers['content-disposition']; |
| if (contentDisposition) { |
| const extendedMatch = contentDisposition.match( |
| /filename\*\s*=\s*(?:utf-8|UTF-8)'[^']*'([^;\s]+)/i, |
| ); |
| if (extendedMatch?.[1]) { |
| return decodeURIComponent(extendedMatch[1]); |
| } |
|
|
| const plainMatch = contentDisposition.match(/filename\s*=\s*["']?([^"';\s]+)["']?/i); |
| if (plainMatch?.[1]) { |
| return decodeURIComponent(plainMatch[1]); |
| } |
| } |
|
|
| return ''; |
| }; |
|
|
| |
| |
| |
| export const fetchWithAuth = async ( |
| url: string, |
| username?: string, |
| password?: string, |
| useProxy = false, |
| options: RequestInit = {}, |
| ): Promise<Response> => { |
| const { |
| url: cleanUrl, |
| username: urlUsername, |
| password: urlPassword, |
| } = extractCredentialsFromURL(url); |
|
|
| const finalUsername = username || urlUsername; |
| const finalPassword = password || urlPassword; |
|
|
| const fetchURL = useProxy ? getProxiedURL(cleanUrl) : cleanUrl; |
| const headers: Record<string, string> = { |
| 'User-Agent': READEST_OPDS_USER_AGENT, |
| Accept: 'application/atom+xml, application/xml, text/xml, */*', |
| ...(options.headers as Record<string, string>), |
| }; |
|
|
| const fetch = isTauriAppPlatform() ? tauriFetch : window.fetch; |
| let res = await fetch(fetchURL, { |
| ...options, |
| method: options.method || 'GET', |
| headers, |
| danger: { acceptInvalidCerts: true, acceptInvalidHostnames: true }, |
| }); |
|
|
| |
| if (!res.ok && (res.status === 401 || res.status === 403) && finalUsername && finalPassword) { |
| const wwwAuthenticate = res.headers.get('WWW-Authenticate'); |
| if (wwwAuthenticate) { |
| let authHeader: string | null = null; |
|
|
| if (wwwAuthenticate.toLowerCase().startsWith('digest')) { |
| const urlObj = new URL(cleanUrl); |
| authHeader = await createDigestAuth( |
| finalUsername, |
| finalPassword, |
| wwwAuthenticate, |
| options.method || 'GET', |
| urlObj.pathname + urlObj.search, |
| ); |
| } else if (wwwAuthenticate.toLowerCase().startsWith('basic')) { |
| authHeader = createBasicAuth(finalUsername, finalPassword); |
| } |
|
|
| if (authHeader) { |
| const finalUrl = useProxy ? `${fetchURL}&auth=${encodeURIComponent(authHeader)}` : fetchURL; |
| res = await fetch(finalUrl, { |
| ...options, |
| method: options.method || 'GET', |
| headers: useProxy ? headers : { ...headers, Authorization: authHeader }, |
| danger: { acceptInvalidCerts: true, acceptInvalidHostnames: true }, |
| }); |
| } |
| } |
| } |
|
|
| return res; |
| }; |
|
|