import { z } from "zod" import { getClaims, getToken } from "@/lib/auth" import { ApiClientError, requestBlob } from "./http-client" // The largest human-only receipt is a PostgreSQL backup, bounded to 64 MiB. const maxDownloadBytes = 64 * 1024 * 1024 const receiptSchema = z.object({ artifactId: z.string().uuid(), humanDownloadOnly: z.literal(true), downloadPath: z.string().optional(), bytes: z.number().int().min(0).max(maxDownloadBytes).optional(), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), }).refine(receipt => (receipt.bytes === undefined) === (receipt.sha256 === undefined)) /** Only structured receipts qualify; supplied paths never become navigation targets. */ export function humanArtifactReceipt(value: unknown) { const parsed = receiptSchema.safeParse(value) if (!parsed.success) return null const path = `/api/mcp/artifacts/${parsed.data.artifactId}` if (parsed.data.downloadPath !== undefined && parsed.data.downloadPath !== path) return null const { artifactId, bytes, sha256 } = parsed.data return { artifactId, path, ...(bytes === undefined ? {} : { bytes, sha256 }) } } async function boundedArtifactBlob(response: Response, artifact: NonNullable>, signal?: AbortSignal) { const size = artifact.bytes const bytes = size === undefined ? undefined : new Uint8Array(size) const chunks: BlobPart[] = [] const reader = response.body?.getReader() let length = 0, finished = false const mismatch = () => new ApiClientError("Файл не соответствует квитанции", 409) if (reader) { try { while (true) { const chunk = await reader.read() signal?.throwIfAborted() if (chunk.done) { finished = true; break } const offset = length length += chunk.value.byteLength if (length > (size ?? maxDownloadBytes)) throw mismatch() if (bytes) bytes.set(chunk.value, offset) else chunks.push(chunk.value) } } finally { if (!finished) void reader.cancel().catch(() => undefined) reader.releaseLock() } } if (size !== undefined && length !== size) throw mismatch() // The backend also verifies the signed receipt for browsers without Web Crypto on plain HTTP. if (bytes && artifact.sha256 && globalThis.crypto?.subtle) { const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes) const sha256 = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("") if (sha256 !== artifact.sha256) throw mismatch() } return new Blob(bytes ? [bytes] : chunks, { type: response.headers.get("Content-Type") ?? "" }) } export async function downloadHumanArtifact(base: string, receipt: unknown, signal?: AbortSignal) { const artifact = humanArtifactReceipt(receipt) if (!artifact) throw new Error("Некорректная квитанция файла") const claims = getClaims() const token = getToken() if (!token || !claims?.sub || !claims.apps?.includes("mm")) { throw new ApiClientError("Войдите в портал для скачивания файла", 401) } const response = await requestBlob(base, artifact.path, { signal, cache: "no-store", redirect: "error" }) const blob = await boundedArtifactBlob(response, artifact, signal) signal?.throwIfAborted() if (getToken() !== token || !getClaims()) throw new ApiClientError("Сеанс портала изменился", 401) const disposition = response.headers.get("Content-Disposition") ?? "" const suggested = /filename="([a-zA-Z0-9._-]{1,200})"/.exec(disposition)?.[1] const filename = suggested && suggested !== "." && suggested !== ".." ? suggested : `mcp-${artifact.artifactId}.bin` const url = URL.createObjectURL(blob) const link = document.createElement("a") try { link.href = url link.download = filename document.body.appendChild(link) link.click() } finally { link.remove() // Let the browser begin consuming the download before releasing the in-memory file. setTimeout(() => URL.revokeObjectURL(url), 1000) } } export function humanArtifactError(error: unknown): string { if (error instanceof ApiClientError) { if (error.status === 401) return "Войдите в портал для скачивания файла." if (error.status === 403) return "Доступ к файлу отозван или файл принадлежит другому пользователю." if (error.status === 404 || error.status === 410) return "Файл отсутствует или срок хранения истёк. Подготовьте новую выгрузку." if (error.status === 409) return "Файл изменился или больше не соответствует квитанции. Подготовьте новую выгрузку." } // Do not render response bodies, filenames, credentials, or binary content as errors. return "Не удалось скачать файл. Проверьте соединение и повторите попытку." }