import { Injectable, UnauthorizedException } from "@nestjs/common"; import { createHmac, timingSafeEqual } from "node:crypto"; import { AsyncLocalStorage } from "node:async_hooks"; /** Short-lived read capabilities, minted only inside authenticated API responses. * Browser image/video/PDF elements cannot attach an Authorization header. */ @Injectable() export class EvidenceAccessService { private digest(path: string, expires: string): string { const secret = process.env.JWT_SECRET; if (!secret) throw new Error("JWT_SECRET is required for evidence access"); return createHmac("sha256", secret) .update(`evidence\n${path}\n${expires}`) .digest("hex"); } sign(value: string): string { const match = value.match( /^(?:https?:\/\/[^/?#]+\/(?:[^?#]*\/)?|(?:\.?\/)?(?:[^\s/?#]+\/)*)files\/([^?#]+)(?:[?#].*)?$/, ); if (!match || !/\.[a-z0-9]+$/i.test(match[1])) return value; const path = match[1]; // Signing uses the same canonical URL path that Express decodes on read. let decoded: string; try { decoded = decodeURIComponent(path); } catch { return value; } const expires = String(Math.floor(Date.now() / 1000) + 3600); return `${value.split(/[?#]/)[0]}?expires=${expires}&signature=${this.digest(decoded, expires)}`; } verify(path: string, expires: string, signature: string): void { if ( typeof path !== "string" || typeof expires !== "string" || typeof signature !== "string" ) throw new UnauthorizedException("نشانی مدرک معتبر نیست."); const exp = Number(expires); if ( !Number.isSafeInteger(exp) || exp <= Date.now() / 1000 || exp > Date.now() / 1000 + 3660 || !/^[a-f0-9]{64}$/.test(signature || "") ) throw new UnauthorizedException( "نشانی مدرک معتبر نیست یا منقضی شده است. پرونده را دوباره باز کنید.", ); if ( !timingSafeEqual( Buffer.from(signature, "hex"), Buffer.from(this.digest(path, expires), "hex"), ) ) throw new UnauthorizedException("دسترسی به این مدرک مجاز نیست."); } /** Only mirror a capability already minted by the trusted file-link builder. * Reflected form fields or arbitrary URL-shaped text cannot mint access. */ project(value: unknown): unknown { const allowed = new Set(); const walk = ( v: unknown, convert: (text: string, field: string) => unknown, field = "", ): unknown => { if (v && typeof (v as any).toObject === "function") return walk((v as any).toObject(), convert, field); if (typeof v === "string") return convert(v, field); if (Array.isArray(v)) return v.map((item) => walk(item, convert, field)); if (v instanceof Map) return Object.fromEntries( [...v].map(([k, item]) => [k, walk(item, convert, String(k))]), ); if ( v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype ) return Object.fromEntries( Object.entries(v).map(([k, item]) => [k, walk(item, convert, k)]), ); return v; }; walk(value, (text) => { if (!text.includes("signature=")) return text; try { const url = new URL(text, "https://evidence.invalid"); const path = decodeURIComponent(url.pathname.split("/files/")[1] || ""); this.verify( path, url.searchParams.get("expires")!, url.searchParams.get("signature")!, ); allowed.add(path); } catch { /* Ordinary text and untrusted links never grant access. */ } return text; }); return walk(value, (text, field) => { if (!/(?:url|urls|path|paths|link|links)$/i.test(field)) return text; try { const url = new URL(text, "https://evidence.invalid"); const path = decodeURIComponent(url.pathname.split("/files/")[1] || ""); return allowed.has(path) ? this.sign(text) : text; } catch { return text; } }); } } export const evidenceRequestScope = new AsyncLocalStorage(); const links = new EvidenceAccessService(); /** Called only when constructing a link from server-owned file metadata. */ export function signAuthorizedEvidenceLink(value: string): string { return evidenceRequestScope.getStore() ? links.sign(value) : value; }