# Storage & CDN Integrations

> External storage and content delivery integration documentation.

---

## Overview

Aphrodite uses cloud storage for media files and CDN for content delivery.

| Service    | Purpose              |
| ---------- | -------------------- |
| AWS S3     | Object storage       |
| CloudFront | CDN delivery         |
| Cloudflare | DDoS protection, WAF |

---

## AWS S3

**API Documentation:** https://docs.aws.amazon.com/s3

### Configuration

```typescript
interface S3Config {
  region: string;
  bucket: string;
  accessKeyId: string;
  secretAccessKey: string;
  endpoint?: string; // For MinIO local dev
}
```

### Initialize Client

```typescript
import { S3Client } from '@aws-sdk/client-s3';

const s3Client = new S3Client({
  region: config.region,
  credentials: {
    accessKeyId: config.accessKeyId,
    secretAccessKey: config.secretAccessKey,
  },
  endpoint: config.endpoint, // Optional for MinIO
});
```

### Generate Presigned Upload URL

```typescript
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

async function getUploadUrl(params: UploadParams): Promise<string> {
  const command = new PutObjectCommand({
    Bucket: config.bucket,
    Key: `uploads/${params.userId}/${params.filename}`,
    ContentType: params.contentType,
    Metadata: {
      'user-id': params.userId,
      'upload-id': params.uploadId,
    },
  });

  return getSignedUrl(s3Client, command, { expiresIn: 3600 });
}
```

### Generate Presigned Download URL

```typescript
import { GetObjectCommand } from '@aws-sdk/client-s3';

async function getDownloadUrl(
  key: string,
  expiresIn: number = 3600
): Promise<string> {
  const command = new GetObjectCommand({
    Bucket: config.bucket,
    Key: key,
  });

  return getSignedUrl(s3Client, command, { expiresIn });
}
```

### Multipart Upload

```typescript
import {
  CreateMultipartUploadCommand,
  UploadPartCommand,
  CompleteMultipartUploadCommand,
} from '@aws-sdk/client-s3';

async function initiateMultipartUpload(key: string): Promise<string> {
  const command = new CreateMultipartUploadCommand({
    Bucket: config.bucket,
    Key: key,
  });

  const response = await s3Client.send(command);
  return response.UploadId!;
}

async function getPartUploadUrl(
  key: string,
  uploadId: string,
  partNumber: number
): Promise<string> {
  const command = new UploadPartCommand({
    Bucket: config.bucket,
    Key: key,
    UploadId: uploadId,
    PartNumber: partNumber,
  });

  return getSignedUrl(s3Client, command, { expiresIn: 3600 });
}
```

### Bucket Structure

```
aphrodite-content/
├── uploads/                    # Temporary uploads
│   └── {userId}/
│       └── {uploadId}/
│           └── {filename}
├── media/                      # Processed media
│   ├── images/
│   │   └── {mediaId}.{ext}
│   └── videos/
│       └── {mediaId}/
│           ├── playlist.m3u8
│           ├── 1080p.m3u8
│           └── segments/
├── thumbnails/                 # Generated thumbnails
│   └── {mediaId}.jpg
├── avatars/                    # User avatars
│   └── {userId}.jpg
└── streams/                    # Stream recordings
    └── {streamId}/
        └── recording.mp4
```

---

## AWS CloudFront

**API Documentation:** https://docs.aws.amazon.com/cloudfront

### Signed URL Generation

```typescript
import { getSignedUrl } from '@aws-sdk/cloudfront-signer';

function generateSignedUrl(url: string, expiresIn: number): string {
  const dateLessThan = new Date(Date.now() + expiresIn * 1000).toISOString();

  return getSignedUrl({
    url,
    dateLessThan,
    keyPairId: config.keyPairId,
    privateKey: config.privateKey,
  });
}
```

### Signed Cookies

```typescript
import { getSignedCookies } from '@aws-sdk/cloudfront-signer';

function generateSignedCookies(
  resourcePath: string,
  expiresIn: number
): SignedCookies {
  const dateLessThan = new Date(Date.now() + expiresIn * 1000).toISOString();

  return getSignedCookies({
    url: `${config.cdnUrl}/${resourcePath}/*`,
    dateLessThan,
    keyPairId: config.keyPairId,
    privateKey: config.privateKey,
  });
}
```

### Cache Invalidation

```typescript
import {
  CloudFrontClient,
  CreateInvalidationCommand,
} from '@aws-sdk/client-cloudfront';

const cfClient = new CloudFrontClient({ region: 'us-east-1' });

async function invalidateCache(paths: string[]): Promise<void> {
  const command = new CreateInvalidationCommand({
    DistributionId: config.distributionId,
    InvalidationBatch: {
      CallerReference: Date.now().toString(),
      Paths: {
        Quantity: paths.length,
        Items: paths,
      },
    },
  });

  await cfClient.send(command);
}
```

---

## Cloudflare

**API Documentation:** https://developers.cloudflare.com

### Configuration

```typescript
interface CloudflareConfig {
  zoneId: string;
  apiToken: string;
}
```

### Purge Cache

```typescript
async function purgeCache(urls: string[]): Promise<void> {
  await fetch(
    `https://api.cloudflare.com/client/v4/zones/${config.zoneId}/purge_cache`,
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${config.apiToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ files: urls }),
    }
  );
}
```

### WAF Rules (Terraform)

```hcl
resource "cloudflare_ruleset" "aphrodite_waf" {
  zone_id = var.zone_id
  name    = "Aphrodite WAF"
  kind    = "zone"
  phase   = "http_request_firewall_custom"

  rules {
    action = "block"
    expression = "(http.request.uri.path contains \"/.env\")"
    description = "Block .env access"
  }

  rules {
    action = "challenge"
    expression = "(cf.threat_score gt 30)"
    description = "Challenge high threat score"
  }
}
```

---

## Local Development (MinIO)

```yaml
# docker-compose.dev.yml
services:
  minio:
    image: minio/minio
    ports:
      - '9000:9000'
      - '9001:9001'
    environment:
      MINIO_ROOT_USER: minioadmin
      MINIO_ROOT_PASSWORD: minioadmin
    command: server /data --console-address ":9001"
    volumes:
      - minio_data:/data
```

---

## Document History

| Date       | Version | Changes                  |
| ---------- | ------- | ------------------------ |
| 2026-01-18 | 1.0.0   | Initial Storage/CDN docs |
