# File Upload Validation System

## Architecture

This validation system is designed to work with a **server-side backend** that handles the actual file type detection using the `file-type` library.

### Why Server-Side Only?

1. **`file-type` is ESM-only** - Cannot be bundled for browser use
2. **Security** - Validation should happen on the server, not client
3. **Reliability** - Server-side validation cannot be bypassed
4. **Performance** - Reduces client-side bundle size

## How It Works

### Client-Side (Browser)
1. User selects file
2. File is sent to server via presigned URL or direct upload
3. Server validates the file buffer

### Server-Side (Backend)
1. Receive file buffer
2. Use `BufferContentValidator` to detect actual MIME type
3. Compare with declared MIME type
4. Return validation result
5. Log validation event via `SecurityLogger`

## Implementation

### For Backend Developers

The `BufferContentValidator` class is designed to be used on your backend:

```typescript
import { BufferContentValidator } from '@/shared/services/validation';

const validator = new BufferContentValidator();

// Detect file type from buffer
const detected = await validator.detectFileType(buffer);

// Validate MIME type
const result = await validator.validateMimeType(buffer, declaredMime);

// Check whitelist
const isAllowed = validator.isAllowedMimeType(mimeType, allowedTypes);
```

### For Frontend Developers

The frontend code in `fileService.ts` calls the backend validation:

```typescript
// This happens on the server/backend
const validationResult = await bufferContentValidator.validateMimeType(
  buffer,
  declaredMime
);

// Log the event
await securityLogger.logValidationEvent({
  // ... event details
});
```

## Files

- **`BufferContentValidator.ts`** - Core validation logic (server-side)
- **`SecurityLogger.ts`** - Audit logging (server-side)
- **`types.ts`** - Shared TypeScript interfaces
- **`index.ts`** - Clean exports

## Testing

Tests use mocked `file-type` to avoid ESM issues:

```typescript
jest.mock('file-type', () => ({
  fileTypeFromBuffer: jest.fn(async (buffer: Buffer) => {
    // Mock implementation
  }),
}));
```

## Next Steps

1. **Backend Integration**: Implement validation endpoint on your backend
2. **API Contract**: Define request/response format for validation
3. **Error Handling**: Handle validation errors gracefully
4. **Logging**: Integrate with your logging service

## Example Backend Implementation

```typescript
// backend/routes/validate-upload.ts
import { BufferContentValidator } from '@/shared/services/validation';

app.post('/api/validate-upload', async (req, res) => {
  const { buffer, declaredMime } = req.body;
  const validator = new BufferContentValidator();
  
  const result = await validator.validateMimeType(buffer, declaredMime);
  
  if (!result.isValid) {
    return res.status(400).json({ error: result.error });
  }
  
  res.json({ success: true });
});
```

---

**Note**: The `file-type` package is only needed on the backend. The frontend uses the validation results from the backend API.
