| 1 | import process from "node:process"; |
| 2 | import { Buffer } from "node:buffer"; |
| 3 | import { isIP } from "node:net"; |
| 4 | import { decodeModuleSource, readCache, writeCache } from "./cache.ts"; |
| 5 | import type { CacheEntry } from "./cache.ts"; |
| 6 | import { getFetchTimeoutMs, NAME, MAX_REDIRECTS, isHttpUrl } from "./constants.ts"; |
| 7 | import { resolveLockRedirects, verifyModuleLock } from "./lock.ts"; |
| 8 | import { downloadAdd, downloadBegin, downloadDone } from "./progress.ts"; |
| 9 | |
| 10 | const reload: boolean = process.env.URL_IMPORT_RELOAD === "1"; |
| 11 | const authTokens = parseAuthTokens(process.env.DENO_AUTH_TOKENS); |
| 12 | |
| 13 | interface AuthToken { |
| 14 | host: string; |
| 15 | matchSubdomains: boolean; |
| 16 | authorization: string; |
| 17 | } |
| 18 | |
| 19 | /** Deno 2.9.8 trims the whole list and splits credentials at the last @. */ |
| 20 | function parseAuthTokens(value: string | undefined): AuthToken[] { |
| 21 | if (value === undefined) return []; |
| 22 | const tokens: AuthToken[] = []; |
| 23 | for (const entry of value.trim().split(";")) { |
| 24 | const separator = entry.lastIndexOf("@"); |
| 25 | if (separator === -1) { |
| 26 | console.error("Badly formed auth token discarded."); |
| 27 | continue; |
| 28 | } |
| 29 | const credentials = entry.slice(0, separator); |
| 30 | const host = entry.slice(separator + 1).toLowerCase(); |
| 31 | const ipv6 = host.match(/^\[([^\]]+)\](?::(\d+))?$/); |
| 32 | const ipv4 = host.match(/^([^:]+)(?::(\d+))?$/); |
| 33 | const address = ipv6?.[1] ?? ipv4?.[1]; |
| 34 | const port = ipv6?.[2] ?? ipv4?.[2]; |
| 35 | // IP addresses match exactly, including equivalent IPv6 spellings. Domain |
| 36 | // suffixes retain their spelling and port; default URL ports are absent. |
| 37 | const ip = address !== undefined && !address.includes("%") && isIP(address) === (ipv6 ? 6 : |
| 38 | (port === undefined || Number(port) <= 65535); |
| 39 | const authority = ip |
| 40 | ? new URL(`http://${ipv6 ? `[${address}]` : address}`).hostname + (port === undefined ? "" |
| 41 | : host.replace(/^\./, ""); |
| 42 | tokens.push({ |
| 43 | host: authority, |
| 44 | matchSubdomains: !ip, |
| 45 | authorization: credentials.includes(":") ? `Basic ${Buffer.from(credentials).toString("base64")}` : `Bearer ${credentials}`, |
| 46 | }); |
| 47 | } |
| 48 | return tokens; |
| 49 | } |
| 50 | |
| 51 | function authorizationForUrl(url: string): string | undefined { |
| 52 | const host = new URL(url).host; |
| 53 | return authTokens.find((token) => token.host === host || |
| 54 | (token.matchSubdomains && host.endsWith(`.${token.host}`)))?.authorization; |
| 55 | } |
| 56 | |
| 57 | function stripRedirectCredentials(headers: Headers, fromUrl: string, toUrl: string): void { |
| 58 | if (new URL(fromUrl).origin === new URL(toUrl).origin) return; |
| 59 | for (const name of ["Authorization", "Proxy-Authorization", "Cookie", "Cookie2"]) { |
| 60 | headers.delete(name); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | export interface FetchOptions { |
| 65 | /** Timeout for requests and response bodies, including sync worker startup; defaults to 60_000 ms. */ |
| 66 | timeoutMs?: number; |
| 67 | /** Request headers override defaults and auth tokens; redirecting across origins removes credentials. */ |
| 68 | headers?: HeadersInit; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Fetch a remote module by URL, returning its source and content type. |
| 73 | * |
| 74 | * Results are cached in Deno's remote module cache (`$DENO_DIR/remote/`) and |
| 75 | * reused on subsequent calls. Pass `URL_IMPORT_RELOAD=1` to bypass the cache. |
| 76 | * |
| 77 | * @param url - The `http://` or `https://` URL to fetch. |
| 78 | * @returns The module source, content type, original URL, and final URL after redirects. |
| 79 | * @throws If the request fails, times out or exceeds the redirect limit. |
| 80 | */ |
| 81 | export async function fetchModule(url: string, options: FetchOptions = {}): Promise<CacheEntry> { |
| 82 | const signal = AbortSignal.timeout(getFetchTimeoutMs(options.timeoutMs)); |
| 83 | const requestHeaders = new Headers(options.headers); |
| 84 | if (!requestHeaders.has("User-Agent")) requestHeaders.set("User-Agent", NAME); |
| 85 | signal.throwIfAborted(); |
| 86 | const normalizedUrl = new URL(url).href; |
| 87 | if (!isHttpUrl(normalizedUrl)) throw new TypeError(`Expected an HTTP(S) module URL: ${url}`); |
| 88 | const lockedChain = resolveLockRedirects(normalizedUrl); |
| 89 | const cached = reload ? null : readCache(lockedChain.at(-1)!); |
| 90 | |
| 91 | if (cached) { |
| 92 | const entry = { ...cached, url: normalizedUrl, redirectChain: [...lockedChain.slice(0, -1), ...cached.redirectChain] }; |
| 93 | if (entry.redirectChain.length > MAX_REDIRECTS + 1) throw new Error(`Too many redirects fetching ${url}`); |
| 94 | verifyModuleLock(entry); |
| 95 | return entry; |
| 96 | } |
| 97 | |
| 98 | downloadAdd(); |
| 99 | downloadBegin(url); |
| 100 | |
| 101 | // Mark the slot done even on error, so counters stay balanced and the |
| 102 | // progress bar can clear (a failed fetch must not orphan a slot). |
| 103 | try { |
| 104 | let currentUrl = lockedChain.at(-1)!; |
| 105 | const redirectChain = [...lockedChain]; |
| 106 | const redirectLocations: string[] = []; |
| 107 | // Locked redirects skip HTTP requests, but must still strip caller credentials. |
| 108 | for (let hop = 1; hop < lockedChain.length; hop++) { |
| 109 | stripRedirectCredentials(requestHeaders, lockedChain[hop - 1], lockedChain[hop]); |
| 110 | } |
| 111 | |
| 112 | // The terminal response needs one request after up to MAX_REDIRECTS hops. |
| 113 | for (let redirects = lockedChain.length - 1; redirects <= MAX_REDIRECTS; redirects++) { |
| 114 | const headers = new Headers(requestHeaders); |
| 115 | // Select credentials for this hop, never forward the previous host's token. |
| 116 | const authorization = headers.has("Authorization") ? undefined : authorizationForUrl(currentUrl); |
| 117 | if (authorization !== undefined) { |
| 118 | try { |
| 119 | if (/[\u0000-\u0008\u000a-\u001f\u007f]/.test(authorization)) throw new TypeError(); |
| 120 | headers.set("Authorization", authorization); |
| 121 | } catch { |
| 122 | // Header validation errors can include the value; keep tokens private. |
| 123 | throw new TypeError("Invalid Authorization header in DENO_AUTH_TOKENS"); |
| 124 | } |
| 125 | } |
| 126 | const res = await fetch(currentUrl, { |
| 127 | headers, |
| 128 | redirect: "manual", |
| 129 | signal, |
| 130 | }); |
| 131 | |
| 132 | if (res.status >= 300 && res.status < 400) { |
| 133 | // Drain the response body to free the connection |
| 134 | await res.body?.cancel(); |
| 135 | const location = res.headers.get("location"); |
| 136 | if (!location) { |
| 137 | throw new Error(`Redirect from ${currentUrl} had no Location header`); |
| 138 | } |
| 139 | if (redirects === MAX_REDIRECTS) throw new Error(`Too many redirects fetching ${url}`); |
| 140 | const nextUrl = new URL(location, currentUrl); |
| 141 | // Match Deno's URL join: a Location without # drops the request fragment. |
| 142 | if (!isHttpUrl(nextUrl.href)) throw new TypeError(`Unsupported redirect URL: ${nextUrl.href}`); |
| 143 | stripRedirectCredentials(requestHeaders, currentUrl, nextUrl.href); |
| 144 | currentUrl = nextUrl.href; |
| 145 | redirectChain.push(currentUrl); |
| 146 | redirectLocations.push(location); |
| 147 | continue; |
| 148 | } |
| 149 | |
| 150 | if (!res.ok) { |
| 151 | await res.body?.cancel(); |
| 152 | throw new Error( |
| 153 | `Failed to fetch ${currentUrl}: ${res.status} ${res.statusText}`, |
| 154 | ); |
| 155 | } |
| 156 | |
| 157 | const contentType = res.headers.get("content-type") || "application/javascript"; |
| 158 | const bytes = new Uint8Array(await res.arrayBuffer()); |
| 159 | const source = decodeModuleSource(bytes, currentUrl, contentType); |
| 160 | |
| 161 | signal.throwIfAborted(); |
| 162 | const entry = { source, contentType, url: normalizedUrl, finalUrl: currentUrl, redirectChain }; |
| 163 | verifyModuleLock(entry); |
| 164 | // Locked hops are not HTTP responses; only publish the downloaded chain. |
| 165 | writeCache(redirectChain.slice(lockedChain.length - 1), bytes, contentType, redirectLocations); |
| 166 | return entry; |
| 167 | } |
| 168 | |
| 169 | throw new Error(`Too many redirects fetching ${url}`); |
| 170 | } finally { |
| 171 | downloadDone(); |
| 172 | } |
| 173 | } |
| 174 | |