Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/services/billing/invoice-download-fetch.server.ts
T

104 lines
3.5 KiB
TypeScript

import { fetchOutboundHttpWithRedirects } from "~/utils/outboundHttp.server";
export const INVOICE_DOWNLOAD_MAX_BYTES = 25 * 1024 * 1024;
export const INVOICE_DOWNLOAD_TIMEOUT_MS = 10_000;
export const INVOICE_DOWNLOAD_TRUSTED_REDIRECT_LIMIT = 3;
const INVOICE_DOWNLOAD_ACCEPT = "application/pdf,application/octet-stream;q=0.9";
type InvoiceDownloadFetchDeps = {
fetchImpl?: typeof fetch;
outboundFetch?: typeof fetchOutboundHttpWithRedirects;
};
/**
* Fetch an invoice file. URLs on the trusted provider origin (Lago) are fetched
* directly — Lago answers Active-Storage blob URLs with a redirect (same-origin
* hop for local disk storage, presigned object-storage URL for S3), so trusted
* hops are followed manually and any off-origin hop is handed to the SSRF-safe
* outbound client, which validates the target as a public host.
*/
export async function fetchInvoiceDownloadFile(
fileUrl: string,
options: { trustedProviderOrigin?: string | null } = {},
deps: InvoiceDownloadFetchDeps = {},
): Promise<Response> {
const trustedOrigin = normalizeOrigin(options.trustedProviderOrigin);
let url = new URL(fileUrl);
for (let hop = 0; hop <= INVOICE_DOWNLOAD_TRUSTED_REDIRECT_LIMIT; hop += 1) {
if (!trustedOrigin || url.origin !== trustedOrigin) {
return await (deps.outboundFetch ?? fetchOutboundHttpWithRedirects)(
url.toString(),
{ headers: { accept: INVOICE_DOWNLOAD_ACCEPT } },
{ timeoutMs: INVOICE_DOWNLOAD_TIMEOUT_MS },
);
}
const response = await (deps.fetchImpl ?? fetch)(url, {
headers: { accept: INVOICE_DOWNLOAD_ACCEPT },
redirect: "manual",
signal: AbortSignal.timeout(INVOICE_DOWNLOAD_TIMEOUT_MS),
});
const location = response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
if (!location) {
return response;
}
void response.body?.cancel().catch(() => undefined);
url = new URL(location, url);
}
throw new Error("Invoice download exceeded the redirect limit.");
}
export function createBoundedInvoiceDownloadBody(
response: Response,
maxBytes = INVOICE_DOWNLOAD_MAX_BYTES,
): ReadableStream<Uint8Array> | null {
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
throw new TypeError("Invoice download limit must be a positive safe integer.");
}
const contentLength = response.headers.get("content-length");
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
void response.body?.cancel().catch(() => undefined);
throw new Error("Invoice download exceeds the configured size limit.");
}
if (!response.body) return null;
const reader = response.body.getReader();
let bytesRead = 0;
return new ReadableStream<Uint8Array>({
async pull(controller) {
try {
const chunk = await reader.read();
if (chunk.done) {
controller.close();
return;
}
bytesRead += chunk.value.byteLength;
if (bytesRead > maxBytes) {
await reader.cancel().catch(() => undefined);
controller.error(new Error("Invoice download exceeds the configured size limit."));
return;
}
controller.enqueue(chunk.value);
} catch (error) {
controller.error(error);
}
},
async cancel(reason) {
await reader.cancel(reason).catch(() => undefined);
},
});
}
function normalizeOrigin(value: string | null | undefined): string | null {
if (!value) return null;
try {
return new URL(value).origin;
} catch {
return null;
}
}