/* eslint-disable no-console */ import { Agent } from "undici"; import { constants } from "crypto"; import Page from "@entity-access/server-pages/dist/Page.js"; import { secureFetch } from "../root-certs/RootCertificates.js"; import Content from "@entity-access/server-pages/dist/Content.js"; import { Readable } from "stream"; const dispatcher = new Agent({ connect: { secureOptions: constants.SSL_OP_LEGACY_SERVER_CONNECT } }); export abstract class HttpProxyPage extends Page { proxy({ hostname = void 0, prefix = void 0 }) { const u = this.request.URL; const url = prefix ? `${prefix}${u.pathname}${u.search}` : `https://${hostname}${u.pathname}${u.search}`; return HttpProxyService.fetch(this, url); } } export default class HttpProxyService { static async fetch(page: Page, url) { try { const rs = await secureFetch(url, { redirect : "follow", dispatcher } as any); const status = rs.status; const headers = {}; let compress = false; let contentType = void 0; for (const [key, value] of rs.headers.entries()) { if (key.startsWith(":")) { continue; } switch(key) { case "keep-alive": case "connection": case "upgrade": case "transfer-encoding": case "alt-svc": continue; case "content-type": contentType = value; headers[key] = value; continue; case "content-length": headers[key] = value; continue; case "content-encoding": if (value === "gzip") { compress = true; } continue; case "cache-control": headers[key] = value; continue; default: if (/^access\-/i.test(key)) { headers[key] = value; } continue; } } const buffer = Buffer.from( await rs.arrayBuffer()); if (status >= 400) { console.error(`Email Content Fetch Failed ${status} for ${url}`); } if (!compress) { headers["content-length"] = buffer.byteLength; } return new Content({ reader: Readable.from([buffer]), headers, contentType, status, suppressLog: true }); } catch (error) { page.cacheControl = "public, max-age=8600, immutable"; console.error(`Email Content Fetch Failed for ${url}`); const cause = error.cause; let body = error.stack ?? error; if (cause) { body += `\n${cause?.stack ?? cause}`; } return new Content({ reader: Readable.from([body]), contentType: "text/plain", status: 500, suppressLog: true }); } } }