import { Body, Controller, Get, Head, HttpCode, Param, Post, Put, Req, Res } from '@nestjs/common'; import type { Request, Response } from 'express'; import { IsArray, IsString } from 'class-validator'; import { BlobsService } from '../application/blobs.service'; import type { PublicUser } from '../domain/models'; import { CurrentUser } from '../auth/auth.decorators'; const ownerOf = (u: PublicUser | undefined): string | null => u?.id ?? null; class DiffDto { @IsArray() @IsString({ each: true }) hashes?: string[]; } // Whoever uploaded a blob chose its stored content type, so we never trust it: // blobs go back as a plain download the browser won't run (octet-stream, // attachment, no sniffing). Otherwise an uploaded HTML file could run as a page // in the API's origin. function sendInert(res: Response, filepath: string): void { res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Disposition', 'attachment'); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Cache-Control', 'private, max-age=31536000, immutable'); res.sendFile(filepath); } // Content-addressed blobs (PDF originals, renders, extracted text). GET/PUT // move raw bytes; diff answers "which of these do you not have yet". @Controller('api/blobs') export class BlobsController { constructor(private readonly service: BlobsService) {} @Post('diff') @HttpCode(200) async diff(@Body() dto: DiffDto) { return { missing: await this.service.diff(dto.hashes ?? []) }; } @Head(':hash') async head(@Param('hash') hash: string, @Res() res: Response, @CurrentUser() user?: PublicUser) { await this.service.resolve(hash, ownerOf(user)); res.status(200).end(); } @Get(':hash') async get(@Param('hash') hash: string, @Res() res: Response, @CurrentUser() user?: PublicUser) { const { filepath } = await this.service.resolve(hash, ownerOf(user)); sendInert(res, filepath); } @Put(':hash') @HttpCode(201) async put(@Param('hash') hash: string, @Req() req: Request, @CurrentUser() user?: PublicUser) { const bytes = req.body as Buffer; const mime = req.headers['content-type'] ?? null; await this.service.store( hash, Buffer.isBuffer(bytes) ? bytes : Buffer.alloc(0), typeof mime === 'string' ? mime : null, ownerOf(user), ); return { hash }; } }