| 4 | import { spawnSync } from "node:child_process"; |
| 5 | import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; |
| 6 | import { tmpdir } from "node:os"; |
| 7 | import { basename, join } from "node:path"; |
| 8 | import process from "node:process"; |
| 9 | import { Worker } from "node:worker_threads"; |
| 10 | import { Buffer } from "node:buffer"; |
| 11 | import { fetchModule } from "./fetch.ts"; |
| 12 | import { cachePaths, decodeModuleSource, readCache, writeCache, writeFileAtomicSync } from "./cache.ts"; |
| 13 |
| 14 | const requests: string[] = []; |
| 15 | const wasmBytes = Uint8Array.from([ |
| 16 | 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 127, 3, 2, 1, 0, |
| 17 | 7, 10, 1, 6, 97, 110, 115, 119, 101, 114, 0, 0, 10, 6, 1, 4, 0, 65, 42, 11, |
| 18 | 0, 3, 1, 120, 255, |
| 19 | ]); |
| 20 | const encodedText = 'export default "café";\n'; |
| 21 | const encodedSources = [ |
| 22 | { path: "/encoding/latin1.mjs", contentType: "application/javascript; charset=iso-8859-1", bytes: Buffer.from(encodedText, "latin1") }, |
| 23 | { path: "/encoding/utf16le.mjs", contentType: 'application/javascript; CHARSET="utf-16le"', bytes: Buffer.concat([Buffer.from([255, 254]), Buffer.from(encodedText, "utf16le")]) }, |
| 24 | { path: "/encoding/utf16be.mjs", contentType: "application/javascript; charset=utf-16be", bytes: Buffer.concat([Buffer.from([254, 255]), Buffer.from(encodedText, "utf16le").swap16()]) }, |
| 25 | { path: "/encoding/bom.mjs", contentType: "application/javascript", bytes: Buffer.concat([Buffer.from([239, 187, 191]), Buffer.from(encodedText)]) }, |
| 26 | ]; |
| 27 | const server = createServer((request, response) => { |
| 28 | requests.push(request.url!); |
| 29 | const encoded = encodedSources.find((entry) => entry.path === request.url); |
| 30 | if (encoded) { |
| 31 | response.setHeader("Content-Type", encoded.contentType); |
| 32 | response.end(encoded.bytes); |
| 33 | return; |
| 34 | } |
| 35 | if (request.url === "/missing.mjs") { |
| 36 | response.writeHead(404).end(); |
| 37 | return; |
| 38 | } |
| 39 | if (request.url?.startsWith("/redirect/")) { |
| 40 | const count = Number(request.url.slice("/redirect/".length)); |
| 41 | if (count > 0) { |
| 42 | response.writeHead(302, { Location: `/redirect/${count - 1}` }).end(); |
| 43 | return; |
| 44 | } |
| 45 | } |
| 46 | if (request.url === "/fragment-redirect") { |
| 47 | response.writeHead(302, { Location: "/fragment-target.mjs" }).end(); |
| 48 | return; |
| 49 | } |
| 50 | if (request.url === "/fragment-replaced") { |
| 51 | response.writeHead(302, { Location: "/replaced-target.mjs#replacement" }).end(); |
| 52 | return; |
| 53 | } |
| 54 | if (request.url === "/fragment-cleared") { |
| 55 | response.writeHead(302, { Location: "/cleared-target.mjs#" }).end(); |
| 56 | return; |
| 57 | } |
| 58 | if (request.url === "/cancelled.mjs") { |
| 59 | response.writeHead(200, { "Content-Type": "application/javascript" }); |
| 60 | response.flushHeaders(); |
| 61 | return; |
| 62 | } |
| 63 | if (request.url === "/invalid-redirect") { |
| 64 | response.writeHead(302, { Location: "data:text/javascript,export default 42" }).end(); |
| 65 | return; |
| 66 | } |
| 67 | if (request.url === "/binary.wasm") { |
| 68 | response.setHeader("Content-Type", "application/wasm"); |
| 69 | response.end(wasmBytes); |
| 70 | return; |
| 71 | } |
| 72 | response.setHeader("Content-Type", "application/javascript"); |
| 73 | response.end(request.url === "/empty.mjs" ? "" : `export default ${JSON.stringify(request.url)};`); |
| 74 | }); |
| 75 | let baseUrl: string; |
| 76 |
| 77 | function runAuthChild(program: string, authTokens?: string, reload = false, lockFile = false) { |
| 78 | const directory = mkdtempSync(join(tmpdir(), "node-url-import-auth-test-")); |
| 79 | try { |
| 80 | const env: NodeJS.ProcessEnv = { |
| 81 | ...process.env, |
| 82 | DENO_DIR: join(directory, "deno"), |
| 83 | URL_IMPORT_RELOAD: reload ? "1" : "0", |
| 84 | URL_IMPORT_LOCK: lockFile ? join(directory, "deno.lock") : "", |
| 85 | URL_IMPORT_FROZEN: "0", |
| 86 | FORCE_COLOR: "0", |
| 87 | }; |
| 88 | if (authTokens === undefined) delete env.DENO_AUTH_TOKENS; |
| 89 | else env.DENO_AUTH_TOKENS = authTokens; |
| 90 | return spawnSync(process.execPath, ["--input-type=module", "--eval", program], { |
| 91 | encoding: "utf8", |
| 92 | timeout: 15_000, |
| 93 | env, |
| 94 | }); |
| 95 | } finally { |
| 96 | rmSync(directory, { recursive: true, force: true }); |
| 97 | } |
| 98 | } |
| 99 |
| 100 | before(async () => { |
| 101 | await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 102 | const address = server.address(); |
| 103 | assert.ok(address && typeof address !== "string"); |
| 104 | baseUrl = `http://127.0.0.1:${address.port}`; |
| 105 | }); |
| 106 | beforeEach(() => { requests.length = 0; }); |
| 107 | after(async () => { |
| 108 | server.closeAllConnections(); |
| 109 | await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve())); |
| 110 | rmSync(cachePaths(baseUrl).dir, { recursive: true, force: true }); |
| 111 | }); |
| 112 |
| 113 | describe("fetchModule", () => { |
| 114 | it("matches DENO_AUTH_TOKENS at the HTTP boundary", () => { |
| 115 | const program = ` |
| 116 | import assert from "node:assert/strict"; |
| 117 | import { fetchModule } from ${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}; |
| 118 |
| 119 | const calls = []; |
| 120 | globalThis.fetch = async (url, options) => { |
| 121 | calls.push({ url: String(url), authorization: new Headers(options.headers).get("authorization") }); |
| 122 | return new Response("export default 1;", { headers: { "content-type": "application/javascript" } }); |
| 123 | }; |
| 124 | const cases = [ |
| 125 | ["https://api.example.test/module.mjs", "https://api.example.test/module.mjs", "Bearer domain-token"], |
| 126 | ["https://sub.api.example.test/module.mjs", "https://sub.api.example.test/module.mjs", "Bearer domain-token"], |
| 127 | ["https://notapi.example.test/module.mjs", "https://notapi.example.test/module.mjs", undefined], |
| 128 | ["https://api.example.test.evil/module.mjs", "https://api.example.test.evil/module.mjs", undefined], |
| 129 | ["https://notexample.test/module.mjs", "https://notexample.test/module.mjs", undefined], |
| 130 | ["https://at.test/module.mjs", "https://at.test/module.mjs", "Bearer last@token"], |
| 131 | ["https://basic.test/module.mjs", "https://basic.test/module.mjs", "Basic YmFzaWM6d2l0aDpjb2xvbnM="], |
| 132 | ["https://first.test/module.mjs", "https://first.test/module.mjs", "Bearer first-match"], |
| 133 | ["https://child.first.test/module.mjs", "https://child.first.test/module.mjs", "Bearer first-match"], |
| 134 | ["https://port.test/module.mjs", "https://port.test/module.mjs", undefined], |
| 135 | ["https://port.test:443/module.mjs", "https://port.test/module.mjs", undefined], |
| 136 | ["https://port.test:8080/module.mjs", "https://port.test:8080/module.mjs", "Bearer custom-port"], |
| 137 | ["https://port.test:8081/module.mjs", "https://port.test:8081/module.mjs", undefined], |
| 138 | ["http://127.0.0.1/module.mjs", "http://127.0.0.1/module.mjs", "Bearer ipv4"], |
| 139 | ["http://127.0.0.1.example.test/module.mjs", "http://127.0.0.1.example.test/module.mjs", undefined], |
| 140 | ["http://127.0.0.2/module.mjs", "http://127.0.0.2/module.mjs", undefined], |
| 141 | ["http://127.000.0.1/module.mjs", "http://127.0.0.1/module.mjs", "Bearer ipv4"], |
| 142 | ["http://[2001:db8::1]/module.mjs", "http://[2001:db8::1]/module.mjs", "Bearer ipv6"], |
| 143 | ["http://[2001:0db8:0:0:0:0:0:1]/module.mjs", "http://[2001:db8::1]/module.mjs", "Bearer ipv6"], |
| 144 | ["http://[2001:db8::2]/module.mjs", "http://[2001:db8::2]/module.mjs", "Bearer ipv6-other"], |
| 145 | ["http://[2001:db8::2]:8080/module.mjs", "http://[2001:db8::2]:8080/module.mjs", "Bearer ipv6-port"], |
| 146 | ["https://untrimmed.test/module.mjs", "https://untrimmed.test/module.mjs", undefined], |
| 147 | ["https://tail.test/module.mjs", "https://tail.test/module.mjs", "Bearer tail"], |
| 148 | ["https://malformed.test/module.mjs", "https://malformed.test/module.mjs", undefined], |
| 149 | ["https://unconfigured.test/module.mjs", "https://unconfigured.test/module.mjs", undefined], |
| 150 | ]; |
| 151 | for (const [input] of cases) await fetchModule(input); |
| 152 | assert.deepEqual(calls.map(({ url, authorization }) => [url, authorization ?? undefined]), |
| 153 | cases.map(([, url, authorization]) => [url, authorization])); |
| 154 |
| 155 | await assert.rejects(fetchModule("https://control.example.test/module.mjs"), (error) => { |
| 156 | assert.equal(error.message, "Invalid Authorization header in DENO_AUTH_TOKENS"); |
| 157 | assert.doesNotMatch(error.message, /private\\ncredential/); |
| 158 | return true; |
| 159 | }); |
| 160 | assert.equal(calls.length, cases.length); |
| 161 | `; |
| 162 | const authTokens = `\n${[ |
| 163 | "domain-token@.API.EXAMPLE.TEST", |
| 164 | "last@token@at.test", |
| 165 | "basic:with:colons@basic.test", |
| 166 | "first-match@first.test", |
| 167 | "second-match@child.first.test", |
| 168 | "default-port@port.test:443", |
| 169 | "custom-port@port.test:8080", |
| 170 | "ipv4@127.0.0.1", |
| 171 | "invalid-ipv4@127.000.0.2", |
| 172 | "ipv6@[2001:db8::1]", |
| 173 | "ipv6-other@[2001:db8::2]", |
| 174 | "ipv6-port@[2001:db8::2]:8080", |
| 175 | "untrimmed@ untrimmed.test ", |
| 176 | "tail@tail.test", |
| 177 | "malformed.test", |
| 178 | "private\ncredential@control.example.test", |
| 179 | ].join(";")}\t`; |
| 180 | const child = runAuthChild(program, authTokens, true); |
| 181 | assert.equal(child.status, 0, `${child.stderr}\n${child.stdout}`); |
| 182 | assert.doesNotMatch(child.stderr, /last@token|basic:with:colons|domain-token|private\ncredential/); |
| 183 | assert.match(child.stderr, /Badly formed auth token discarded/); |
| 184 | }); |
| 185 |
| 186 | it("reuses authenticated cache entries without another request", () => { |
| 187 | const program = ` |
| 188 | import assert from "node:assert/strict"; |
| 189 | import { fetchModule } from ${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}; |
| 190 | import { readCache } from ${JSON.stringify(new URL("./cache.ts", import.meta.url).href)}; |
| 191 | const calls = []; |
| 192 | globalThis.fetch = async (url, options) => { |
| 193 | calls.push({ url: String(url), authorization: new Headers(options.headers).get("authorization") }); |
| 194 | return new Response("export default 1;", { headers: { "content-type": "application/javascript" } }); |
| 195 | }; |
| 196 | const url = "https://cache-auth.example.test/cached.mjs"; |
| 197 | const first = await fetchModule(url); |
| 198 | const second = await fetchModule(url); |
| 199 | assert.deepEqual(second, first); |
| 200 | assert.deepEqual(calls, [{ url, authorization: "Bearer cached" }]); |
| 201 | assert.ok(readCache(url)); |
| 202 | `; |
| 203 | const child = runAuthChild(program, "cached@cache-auth.example.test"); |
| 204 | assert.equal(child.status, 0, `${child.stderr}\n${child.stdout}`); |
| 205 | assert.doesNotMatch(child.stderr, /cached/); |
| 206 | }); |
| 207 |
| 208 | it("does not add credentials when DENO_AUTH_TOKENS was unset at module startup", () => { |
| 209 | const program = ` |
| 210 | import assert from "node:assert/strict"; |
| 211 | import process from "node:process"; |
| 212 | import { fetchModule } from ${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}; |
| 213 | const calls = []; |
| 214 | globalThis.fetch = async (url, options) => { |
| 215 | calls.push(new Headers(options.headers).get("authorization")); |
| 216 | return new Response("export default 1;", { headers: { "content-type": "application/javascript" } }); |
| 217 | }; |
| 218 | process.env.DENO_AUTH_TOKENS = "late@unset.example.test"; |
| 219 | await fetchModule("https://unset.example.test/module.mjs"); |
| 220 | assert.deepEqual(calls, [null]); |
| 221 | `; |
| 222 | const child = runAuthChild(program); |
| 223 | assert.equal(child.status, 0, `${child.stderr}\n${child.stdout}`); |
| 224 | }); |
| 225 |
| 226 | it("does not cache failed authenticated responses", () => { |
| 227 | const program = ` |
| 228 | import assert from "node:assert/strict"; |
| 229 | import { fetchModule } from ${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}; |
| 230 | import { readCache } from ${JSON.stringify(new URL("./cache.ts", import.meta.url).href)}; |
| 231 | const url = "https://private.example.test/failures.mjs"; |
| 232 | let requests = 0; |
| 233 | globalThis.fetch = async (_url, options) => { |
| 234 | assert.equal(new Headers(options.headers).get("authorization"), "Bearer private-token"); |
| 235 | requests++; |
| 236 | if (requests === 1) return new Response("denied", { status: 401, statusText: "Unauthorized" }); |
| 237 | if (requests === 2) return new Response("missing", { status: 404, statusText: "Not Found" }); |
| 238 | return new Response("export default 42;", { headers: { "content-type": "application/javascript" } }); |
| 239 | }; |
| 240 | await assert.rejects(fetchModule(url), /401 Unauthorized/); |
| 241 | assert.equal(readCache(url), null); |
| 242 | await assert.rejects(fetchModule(url), /404 Not Found/); |
| 243 | assert.equal(readCache(url), null); |
| 244 | assert.equal((await fetchModule(url)).source, "export default 42;"); |
| 245 | assert.ok(readCache(url)); |
| 246 | assert.equal(requests, 3); |
| 247 | `; |
| 248 | const child = runAuthChild(program, "private-token@private.example.test"); |
| 249 | assert.equal(child.status, 0, `${child.stderr}\n${child.stdout}`); |
| 250 | assert.doesNotMatch(child.stderr, /private-token/); |
| 251 | }); |
| 252 |
| 253 | it("accepts HeadersInit forms and lets explicit headers override defaults and auth tokens", () => { |
| 254 | const program = ` |
| 255 | import assert from "node:assert/strict"; |
| 256 | import { fetchModule } from ${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}; |
| 257 | const calls = []; |
| 258 | globalThis.fetch = async (url, options) => { |
| 259 | calls.push({ url: String(url), headers: new Headers(options.headers) }); |
| 260 | return new Response("export default 1;", { headers: { "content-type": "application/javascript" } }); |
| 261 | }; |
| 262 | const headers = new Headers([["X-Request", "headers-instance"]]); |
| 263 | await fetchModule("https://headers.example.test/record.mjs", { |
| 264 | headers: { "User-Agent": "caller-agent", "X-Request": "record", Authorization: "Basic caller" }, |
| 265 | }); |
| 266 | await fetchModule("https://headers.example.test/tuples.mjs", { |
| 267 | headers: [["X-Request", "tuples"]], |
| 268 | }); |
| 269 | await fetchModule("https://headers.example.test/headers.mjs", { headers }); |
| 270 | assert.deepEqual(calls.map(({ headers }) => [ |
| 271 | headers.get("user-agent"), headers.get("x-request"), headers.get("authorization"), |
| 272 | ]), [ |
| 273 | ["caller-agent", "record", "Basic caller"], |
| 274 | ["node-url-import", "tuples", "Bearer configured-token"], |
| 275 | ["node-url-import", "headers-instance", "Bearer configured-token"], |
| 276 | ]); |
| 277 | assert.equal(headers.get("authorization"), null); |
| 278 | assert.equal(headers.get("user-agent"), null); |
| 279 | `; |
| 280 | const child = runAuthChild(program, "configured-token@headers.example.test", true); |
| 281 | assert.equal(child.status, 0, `${child.stderr}\n${child.stdout}`); |
| 282 | }); |
| 283 |
| 284 | it("validates timeout and headers options even on cache hits", () => { |
| 285 | const program = ` |
| 286 | import assert from "node:assert/strict"; |
| 287 | import { fetchModule } from ${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}; |
| 288 | import { writeCache } from ${JSON.stringify(new URL("./cache.ts", import.meta.url).href)}; |
| 289 | let fetchCalls = 0; |
| 290 | globalThis.fetch = async () => { |
| 291 | fetchCalls++; |
| 292 | return new Response("export default 1;", { |
| 293 | headers: { "content-type": "application/javascript" }, |
| 294 | }); |
| 295 | }; |
| 296 | const url = "https://timeout.example.test/module.mjs"; |
| 297 | writeCache([url], "export default 1;", "application/javascript"); |
| 298 | for (const timeoutMs of [0, -1, 1.5, NaN, Infinity, 2147483648]) { |
| 299 | await assert.rejects(fetchModule(url, { timeoutMs }), { |
| 300 | name: "RangeError", |
| 301 | message: "The fetch timeout must be a positive integer no greater than 2147483647", |
| 302 | }); |
| 303 | } |
| 304 | await assert.rejects(fetchModule(url, { headers: [["invalid header name", "value"]] }), TypeError); |
| 305 | assert.equal((await fetchModule(url, { timeoutMs: 2147483647 })).source, "export default 1;"); |
| 306 | assert.equal(fetchCalls, 0); |
| 307 | `; |
| 308 | const child = runAuthChild(program); |
| 309 | assert.equal(child.status, 0, `${child.stderr}\n${child.stdout}`); |
| 310 | }); |
| 311 |
| 312 | it("preserves caller headers on same-origin redirects and filters credentials across origins", () => { |
| 313 | const program = ` |
| 314 | import assert from "node:assert/strict"; |
| 315 | import { fetchModule } from ${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}; |
| 316 | const calls = []; |
| 317 | globalThis.fetch = async (url, options) => { |
| 318 | const href = String(url); |
| 319 | const headers = new Headers(options.headers); |
| 320 | calls.push({ url: href, headers }); |
| 321 | if (href === "https://same.example.test/start.mjs") { |
| 322 | return new Response(null, { status: 302, headers: { location: "/finish.mjs" } }); |
| 323 | } |
| 324 | if (href === "https://source.example.test/start.mjs") { |
| 325 | return new Response(null, { status: 302, headers: { location: "https://target.example.test/finish.mjs" } }); |
| 326 | } |
| 327 | return new Response("export default 1;", { headers: { "content-type": "application/javascript" } }); |
| 328 | }; |
| 329 |
| 330 | const sameOriginHeaders = { |
| 331 | Authorization: "Basic caller", |
| 332 | "Proxy-Authorization": "Basic proxy", |
| 333 | Cookie: "session=same-origin", |
| 334 | Cookie2: "legacy=same-origin", |
| 335 | "X-Request": "same-origin", |
| 336 | }; |
| 337 | await fetchModule("https://same.example.test/start.mjs", { headers: sameOriginHeaders }); |
| 338 | assert.equal(calls[0].headers.get("authorization"), "Basic caller"); |
| 339 | assert.equal(calls[1].headers.get("authorization"), "Basic caller"); |
| 340 | assert.equal(calls[1].headers.get("proxy-authorization"), "Basic proxy"); |
| 341 | assert.equal(calls[1].headers.get("cookie"), "session=same-origin"); |
| 342 | assert.equal(calls[1].headers.get("cookie2"), "legacy=same-origin"); |
| 343 | assert.equal(calls[1].headers.get("x-request"), "same-origin"); |
| 344 | assert.deepEqual(sameOriginHeaders, { |
| 345 | Authorization: "Basic caller", |
| 346 | "Proxy-Authorization": "Basic proxy", |
| 347 | Cookie: "session=same-origin", |
| 348 | Cookie2: "legacy=same-origin", |
| 349 | "X-Request": "same-origin", |
| 350 | }); |
| 351 |
| 352 | await fetchModule("https://source.example.test/start.mjs", { |
| 353 | headers: { |
| 354 | Authorization: "Basic caller-cross-origin", |
| 355 | "Proxy-Authorization": "Basic proxy", |
| 356 | Cookie: "session=cross-origin", |
| 357 | Cookie2: "legacy=cross-origin", |
| 358 | "X-Request": "cross-origin", |
| 359 | }, |
| 360 | }); |
| 361 | assert.equal(calls[2].headers.get("authorization"), "Basic caller-cross-origin"); |
| 362 | assert.equal(calls[2].headers.get("proxy-authorization"), "Basic proxy"); |
| 363 | assert.equal(calls[2].headers.get("cookie"), "session=cross-origin"); |
| 364 | assert.equal(calls[2].headers.get("cookie2"), "legacy=cross-origin"); |
| 365 | assert.equal(calls[3].headers.get("authorization"), "Bearer target-token"); |
| 366 | assert.equal(calls[3].headers.get("proxy-authorization"), null); |
| 367 | assert.equal(calls[3].headers.get("cookie"), null); |
| 368 | assert.equal(calls[3].headers.get("cookie2"), null); |
| 369 | assert.equal(calls[3].headers.get("x-request"), "cross-origin"); |
| 370 |
| 371 | const { writeFileSync } = await import("node:fs"); |
| 372 | const start = "https://locked-a.example.test/start.mjs"; |
| 373 | const middle = "https://locked-b.example.test/middle.mjs"; |
| 374 | const final = "https://locked-a.example.test/final.mjs"; |
| 375 | const { default: process } = await import("node:process"); |
| 376 | writeFileSync(process.env.URL_IMPORT_LOCK, JSON.stringify({ |
| 377 | version: "5", |
| 378 | redirects: { [start]: middle, [middle]: final }, |
| 379 | remote: {}, |
| 380 | })); |
| 381 | const { fetchModule: fetchLockedModule } = await import(${JSON.stringify(new URL("./fetch.ts", import.meta.url).href)}); |
| 382 | await fetchLockedModule(start, { headers: { |
| 383 | Authorization: "Basic locked-caller", |
| 384 | "Proxy-Authorization": "Basic locked-proxy", |
| 385 | Cookie: "session=locked", |
| 386 | Cookie2: "legacy=locked", |
| 387 | "X-Request": "locked-chain", |
| 388 | } }); |
| 389 | assert.equal(calls[4].url, final); |
| 390 | assert.equal(calls[4].headers.get("authorization"), "Bearer locked-a-token"); |
| 391 | assert.equal(calls[4].headers.get("proxy-authorization"), null); |
| 392 | assert.equal(calls[4].headers.get("cookie"), null); |
| 393 | assert.equal(calls[4].headers.get("cookie2"), null); |
| 394 | assert.equal(calls[4].headers.get("x-request"), "locked-chain"); |
| 395 | `; |
| 396 | const child = runAuthChild(program, |
| 397 | "source-token@source.example.test;target-token@target.example.test;locked-a-token@locked-a.example.test", |
| 398 | true, true); |
| 399 | assert.equal(child.status, 0, `${child.stderr}\n${child.stdout}`); |
| 400 | }); |
| 401 |
| 402 | it("rejects unsuccessful responses without preventing later downloads", async () => { |
| 403 | await assert.rejects(fetchModule(`${baseUrl}/missing.mjs`)); |
| 404 | const result = await fetchModule(`${baseUrl}/available.mjs`); |
| 405 | assert.equal(result.source, 'export default "/available.mjs";'); |
| 406 | }); |
| 407 |
| 408 | it("caches query variants independently", async () => { |
| 409 | const firstUrl = `${baseUrl}/module.mjs?target=node`; |
| 410 | const secondUrl = `${baseUrl}/module.mjs?target=es2022`; |
| 411 | const first = await fetchModule(firstUrl); |
| 412 | const second = await fetchModule(secondUrl); |
| 413 | assert.notEqual(first.source, second.source); |
| 414 | assert.equal(first.finalUrl, firstUrl); |
| 415 | assert.equal(second.finalUrl, secondUrl); |
| 416 | assert.deepEqual(requests, ["/module.mjs?target=node", "/module.mjs?target=es2022"]); |
| 417 | assert.equal((await fetchModule(firstUrl)).source, first.source); |
| 418 | assert.equal((await fetchModule(secondUrl)).source, second.source); |
| 419 | assert.equal(requests.length, 2); |
| 420 | }); |
| 421 |
| 422 | it("keeps fragment module identities while sharing their response bytes", async () => { |
| 423 | const url = `${baseUrl}/fragments.mjs`; |
| 424 | const first = await fetchModule(`${url}#first`); |
| 425 | const second = await fetchModule(`${url}#second`); |
| 426 | assert.equal(first.source, second.source); |
| 427 | assert.equal(second.url, `${url}#second`); |
| 428 | assert.equal(second.finalUrl, `${url}#second`); |
| 429 | const modules = await Promise.all([import(`${url}#first`), import(`${url}#second`)]); |
| 430 | assert.notEqual(modules[0], modules[1]); |
| 431 | const raw = readFileSync(cachePaths(url).file); |
| 432 | const marker = Buffer.from("\n// denoCacheMetadata="); |
| 433 | const metadata = JSON.parse(raw.subarray(raw.lastIndexOf(marker) + marker.length).toString("utf8")); |
| 434 | assert.equal(metadata.url, `${url}#first`); |
| 435 | assert.equal(requests.length, 1); |
| 436 | }); |
| 437 |
| 438 | it("caches and loads empty modules", async () => { |
| 439 | const url = `${baseUrl}/empty.mjs`; |
| 440 | assert.equal((await fetchModule(url)).source, ""); |
| 441 | assert.equal((await fetchModule(url)).source, ""); |
| 442 | assert.deepEqual(Object.keys(await import(url)), []); |
| 443 | assert.equal(requests.length, 1); |
| 444 | }); |
| 445 |
| 446 | it("preserves binary bytes through fetching, caching and module loading", async () => { |
| 447 | const url = `${baseUrl}/binary.wasm`; |
| 448 | const first = await fetchModule(url); |
| 449 | assert.ok(first.source instanceof Uint8Array); |
| 450 | assert.deepEqual(first.source, wasmBytes); |
| 451 | const cached = await fetchModule(url); |
| 452 | assert.ok(cached.source instanceof Uint8Array); |
| 453 | assert.deepEqual([...cached.source], [...wasmBytes]); |
| 454 | assert.equal((await import(url)).answer(), 42); |
| 455 | assert.equal(requests.length, 1); |
| 456 | }); |
| 457 |
| 458 | it("decodes response charsets while retaining raw bytes in the shared Deno cache", async () => { |
| 459 | for (const encoded of encodedSources) { |
| 460 | const url = `${baseUrl}${encoded.path}`; |
| 461 | const downloaded = await fetchModule(url); |
| 462 | const cached = await fetchModule(url); |
| 463 | assert.equal(downloaded.source, encodedText); |
| 464 | assert.deepEqual(cached, downloaded); |
| 465 | assert.equal((await import(url)).default, "café"); |
| 466 | const raw = readFileSync(cachePaths(url).file); |
| 467 | assert.deepEqual(raw.subarray(0, encoded.bytes.length), encoded.bytes); |
| 468 | assert.equal(requests.filter((path) => path === encoded.path).length, 1); |
| 469 | } |
| 470 | }); |
| 471 |
| 472 | it("uses Deno's charset labels and strips only a decoded leading BOM", () => { |
| 473 | const url = "https://encoding.test/mod.mjs"; |
| 474 | assert.equal(decodeModuleSource(Buffer.from([128]), url, "application/javascript; charset=iso-8859-1"), "€"); |
| 475 | assert.equal(decodeModuleSource(Buffer.from("\uFEFF\uFEFFtext"), url, "application/javascript"), "\uFEFFtext"); |
| 476 | assert.equal(decodeModuleSource(Buffer.from([72, 101, 255, 108, 111]), url, "application/javascript"), "He�lo"); |
| 477 | assert.throws(() => decodeModuleSource(Buffer.from("text"), url, "application/javascript; charset=utf-32le")); |
| 478 | }); |
| 479 |
| 480 | it("preserves existing file permissions without bypassing umask for new files", { skip: process.platform === "win32" }, () => { |
| 481 | const directory = mkdtempSync(join(tmpdir(), "node-url-import-mode-test-")); |
| 482 | const path = join(directory, "deno.lock"); |
| 483 | const newPath = join(directory, "new.lock"); |
| 484 | const previousUmask = process.umask(0o022); |
| 485 | try { |
| 486 | writeFileSync(path, "old"); |
| 487 | chmodSync(path, 0o660); |
| 488 | writeFileAtomicSync(path, "updated"); |
| 489 | assert.equal(statSync(path).mode & 0o777, 0o660); |
| 490 | assert.equal(readFileSync(path, "utf8"), "updated"); |
| 491 | writeFileAtomicSync(newPath, "created"); |
| 492 | assert.equal(statSync(newPath).mode & 0o777, 0o644); |
| 493 | } finally { |
| 494 | process.umask(previousUmask); |
| 495 | rmSync(directory, { recursive: true, force: true }); |
| 496 | } |
| 497 | }); |
| 498 |
| 499 | it("allows ten redirects but rejects an eleventh without caching the response", async () => { |
| 500 | assert.equal((await fetchModule(`${baseUrl}/redirect/10`)).finalUrl, `${baseUrl}/redirect/0`); |
| 501 | await assert.rejects(fetchModule(`${baseUrl}/redirect/11`)); |
| 502 | assert.equal(readCache(`${baseUrl}/redirect/11`), null); |
| 503 | }); |
| 504 |
| 505 | it("drops request fragments on redirects without a fragment, like Deno", async () => { |
| 506 | const first = await fetchModule(`${baseUrl}/fragment-redirect#first`); |
| 507 | const second = await fetchModule(`${baseUrl}/fragment-redirect#second`); |
| 508 | assert.equal(first.finalUrl, `${baseUrl}/fragment-target.mjs`); |
| 509 | assert.equal(second.finalUrl, first.finalUrl); |
| 510 | assert.deepEqual(first.redirectChain, [`${baseUrl}/fragment-redirect#first`, first.finalUrl]); |
| 511 | assert.deepEqual(second.redirectChain, [`${baseUrl}/fragment-redirect#second`, second.finalUrl]); |
| 512 | assert.deepEqual(requests, ["/fragment-redirect", "/fragment-target.mjs"]); |
| 513 | }); |
| 514 |
| 515 | it("keeps explicit fragment replacements and removals when reading redirect stubs", async () => { |
| 516 | for (const [path, expected] of [["/fragment-replaced", "/replaced-target.mjs#replacement"], ["/fragment-cleared", "/cleared-target.mjs#"]]) { |
| 517 | const first = await fetchModule(`${baseUrl}${path}#original`); |
| 518 | const second = await fetchModule(`${baseUrl}${path}#other`); |
| 519 | assert.equal(first.finalUrl, `${baseUrl}${expected}`); |
| 520 | assert.equal(second.finalUrl, first.finalUrl); |
| 521 | } |
| 522 | assert.equal(requests.length, 4); |
| 523 | }); |
| 524 |
| 525 | it("times out stalled response bodies without caching partial source", async () => { |
| 526 | const url = `${baseUrl}/cancelled.mjs`; |
| 527 | await assert.rejects(fetchModule(url, { timeoutMs: 30 })); |
| 528 | assert.equal(readCache(url), null); |
| 529 | assert.equal((await fetchModule(`${baseUrl}/after-cancellation.mjs`)).source, 'export default "/after-cancellation.mjs";'); |
| 530 | }); |
| 531 |
| 532 | it("rejects redirects to non-HTTP module schemes", async () => { |
| 533 | await assert.rejects(fetchModule(`${baseUrl}/invalid-redirect`)); |
| 534 | assert.equal(readCache(`${baseUrl}/invalid-redirect`), null); |
| 535 | }); |
| 536 |
| 537 | it("exports the legacy loader as a resolvable package subpath", () => { |
| 538 | assert.equal(import.meta.resolve("node-url-import/loader"), new URL("../dist/loader.js", import.meta.url).href); |
| 539 | }); |
| 540 |
| 541 | it("uses Deno's unambiguous host and port cache directory names", () => { |
| 542 | const paths = cachePaths("http://127.0.0.1:49653/module.mjs?v=1"); |
| 543 | assert.ok(paths.dir.endsWith("127.0.0.1_port_49653")); |
| 544 | assert.ok(paths.file.endsWith("b22a08393817249b690133d8752be02b19e58c8ebe530a7b4d67a4d3eacaaa93")); |
| 545 | assert.ok(cachePaths("http://api_8080/mod.mjs").dir.endsWith("api%5f8080")); |
| 546 | assert.ok(cachePaths("http://api:8080/mod.mjs").dir.endsWith("api_port_8080")); |
| 547 | assert.notEqual(cachePaths("http://api_port_8080/mod.mjs").dir, cachePaths("http://api:8080/mod.mjs").dir); |
| 548 | assert.ok(cachePaths("http://[::1]:8080/mod.mjs").dir.endsWith("[::1]_port_8080")); |
| 549 | const longHost = Array.from({ length: 3 }, () => "_".repeat(60)).join("."); |
| 550 | const hashed = basename(cachePaths(`http://${longHost}/mod.mjs`).dir); |
| 551 | assert.match(hashed, /^#[a-f0-9]{64}$/); |
| 552 | assert.notEqual(hashed, basename(cachePaths(`http://${longHost}:8080/mod.mjs`).dir)); |
| 553 | }); |
| 554 |
| 555 | it("distinguishes an explicitly empty query in cache keys, like Deno", () => { |
| 556 | assert.notEqual(cachePaths("https://query.test/mod.mjs").file, cachePaths("https://query.test/mod.mjs?").file); |
| 557 | assert.equal(cachePaths("https://query.test/mod.mjs?").file, cachePaths("https://query.test/mod.mjs?#identity").file); |
| 558 | }); |
| 559 |
| 560 | it("does not execute Deno's cached 404 or incomplete redirect stubs as empty modules", async () => { |
| 561 | const url = `${baseUrl}/missing.mjs`; |
| 562 | writeCache([url], "", "application/javascript"); |
| 563 | const path = cachePaths(url).file; |
| 564 | for (const headers of [{ "x-deno-not-found": "404" }, { location: "" }]) { |
| 565 | writeFileSync(path, "\n// denoCacheMetadata=" + JSON.stringify({ url, headers, time: Math.floor(Date.now() / 1000) })); |
| 566 | assert.equal(readCache(url), null); |
| 567 | await assert.rejects(fetchModule(url)); |
| 568 | } |
| 569 | }); |
| 570 |
| 571 | it("rejects incomplete cache writes instead of executing partial source", () => { |
| 572 | const url = `${baseUrl}/incomplete.mjs`; |
| 573 | writeCache([url], "export default 1;", "application/javascript"); |
| 574 | const path = cachePaths(url).file; |
| 575 | const complete = readFileSync(path); |
| 576 | writeFileSync(path, complete.subarray(0, 10)); |
| 577 | assert.equal(readCache(url), null); |
| 578 | }); |
| 579 |
| 580 | it("never exposes partially written entries to concurrent readers", async () => { |
| 581 | const url = `${baseUrl}/concurrent.mjs`; |
| 582 | const source = "export default 1;\n" + " ".repeat(2 * 1024 * 1024); |
| 583 | writeCache([url], source, "application/javascript"); |
| 584 | const signal = new Int32Array(new SharedArrayBuffer(4)); |
| 585 | const writer = new Worker(` |
| 586 | const { workerData } = await import("node:worker_threads"); |
| 587 | const { writeCache } = await import(workerData.cacheUrl); |
| 588 | try { |
| 589 | for (let index = 0; index < 12; index++) { |
| 590 | writeCache([workerData.url], workerData.source, "application/javascript"); |
| 591 | } |
| 592 | } finally { |
| 593 | Atomics.store(new Int32Array(workerData.signal), 0, 1); |
| 594 | } |
| 595 | `, { |
| 596 | eval: true, |
| 597 | execArgv: [], |
| 598 | workerData: { cacheUrl: new URL("./cache.ts", import.meta.url).href, url, source, signal: signal.buffer }, |
| 599 | }); |
| 600 | try { |
| 601 | const deadline = Date.now() + 10_000; |
| 602 | while (Atomics.load(signal, 0) === 0 && Date.now() < deadline) { |
| 603 | const entry = readCache(url); |
| 604 | assert.ok(entry && typeof entry.source === "string"); |
| 605 | assert.equal(Buffer.byteLength(entry.source), Buffer.byteLength(source)); |
| 606 | assert.equal(entry.source, source); |
| 607 | } |
| 608 | assert.equal(Atomics.load(signal, 0), 1); |
| 609 | } finally { |
| 610 | await writer.terminate(); |
| 611 | } |
| 612 | }); |
| 613 | }); |
| 614 |