Address remaining audit findings

Multiple files per transfer
- The UI accepted several files but only files[0] was ever uploaded, so
  recipients saw a list and received one file. Chunks now carry a
  fileIndex, the upload session tracks each file separately, and finalize
  assembles one encrypted payload and one File row per file.
- The download page lists real files with per-file download buttons; the
  previously unused isFileDownloading/isFileDownloaded helpers now drive
  that state. /api/file/[id] accepts a fileId, scoped to the transfer so
  an id from another transfer cannot be fetched.

Large downloads
- Replace res.blob() with a helper that streams the response body to disk
  via the File System Access API where available, keeping peak memory at
  roughly one chunk instead of the whole file. Falls back to the blob
  path elsewhere.

Password brute force
- Rate limit /api/verify and /api/file/[id] to 10 attempts per transfer,
  per client, per 15 minutes; a correct password clears the counter.
  Per-process state, matching the existing local-disk storage model.

Disk reclamation
- Nothing ever deleted payloads, so every transfer stayed on disk
  regardless of expiresAt. Add a cleanup routine that marks lapsed
  transfers EXPIRED, deletes payloads for expired and soft-deleted
  transfers, and sweeps abandoned chunk directories. It refuses to unlink
  anything outside UPLOAD_DIR. Exposed as POST /api/cron/cleanup behind
  CRON_SECRET, failing closed when that is unset.

Build hygiene
- Stop ignoring ESLint during builds and fix all 70 resulting violations:
  unused imports and state, unescaped JSX entities, explicit any, and a
  missing useEffect dependency. Seven catch blocks discarded their error
  silently and now log it.
- Delete dead code: two unused send components, the two legacy upload
  endpoints they called, the unused whole-file WebCrypto helpers, and a
  duplicate separator component differing only by a typo.

Add .env.example documenting configuration, including CRON_SECRET.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
twotalesanimation
2026-08-08 09:32:37 +02:00
parent 2d0c33a45b
commit 0b56ec31ed
25 changed files with 844 additions and 1974 deletions
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from 'next/server'
import crypto from 'crypto'
import { runCleanup } from '@/lib/cleanup'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
function timingSafeEquals(a: string, b: string): boolean {
const bufA = Buffer.from(a)
const bufB = Buffer.from(b)
if (bufA.length !== bufB.length) return false
return crypto.timingSafeEqual(bufA, bufB)
}
/**
* Deletes payloads for expired and soft-deleted transfers.
*
* Intended to be called on a schedule (cron, Vercel Cron, systemd timer):
* curl -X POST -H "Authorization: Bearer $CRON_SECRET" https://host/api/cron/cleanup
*
* Fails closed: without CRON_SECRET set, the endpoint refuses to run rather
* than exposing bulk deletion unauthenticated.
*/
export async function POST(req: NextRequest) {
const secret = process.env.CRON_SECRET
if (!secret) {
console.error('CRON_SECRET is not configured; refusing to run cleanup')
return NextResponse.json({ error: 'Cleanup is not configured' }, { status: 503 })
}
const header = req.headers.get('authorization') || ''
const provided = header.startsWith('Bearer ') ? header.slice(7) : ''
if (!provided || !timingSafeEquals(provided, secret)) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const report = await runCleanup()
console.log('Cleanup report:', report)
return NextResponse.json({ success: true, ...report })
} catch (err) {
console.error('Cleanup failed:', err)
return NextResponse.json({ error: 'Cleanup failed' }, { status: 500 })
}
}
+31 -3
View File
@@ -4,6 +4,11 @@ import bcrypt from 'bcrypt'
import fs from 'fs/promises'
import { TransferStatus } from '@prisma/client'
import { decryptFileStream } from '@/lib/server-encryption'
import { rateLimit, resetRateLimit, clientKey } from '@/lib/rate-limit'
// 10 password attempts per transfer, per client, per 15 minutes.
const ATTEMPT_LIMIT = 10
const ATTEMPT_WINDOW_MS = 15 * 60 * 1000
// Node APIs (fs handles, crypto) — this route cannot run on the edge runtime.
export const runtime = 'nodejs'
@@ -33,9 +38,13 @@ export async function POST(
}
let password = ''
let requestedFileId: number | undefined
try {
const body = await req.json()
password = typeof body?.password === 'string' ? body.password : ''
if (typeof body?.fileId === 'number' && Number.isInteger(body.fileId)) {
requestedFileId = body.fileId
}
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 })
}
@@ -44,6 +53,15 @@ export async function POST(
return NextResponse.json({ error: 'Password required' }, { status: 401 })
}
const rateKey = `file:${id}:${clientKey(req.headers)}`
const limit = rateLimit(rateKey, ATTEMPT_LIMIT, ATTEMPT_WINDOW_MS)
if (!limit.allowed) {
return NextResponse.json(
{ error: 'Too many attempts. Please try again later.' },
{ status: 429, headers: { 'Retry-After': String(limit.retryAfter) } }
)
}
const transfer = await prisma.transfer.findUnique({
where: { downloadUrl: id },
include: { files: true },
@@ -79,7 +97,17 @@ export async function POST(
return NextResponse.json({ error: 'Incorrect password' }, { status: 401 })
}
const file = transfer.files[0]
resetRateLimit(rateKey)
// Pick the requested file, scoped to this transfer so a file id from another
// transfer cannot be fetched. Defaults to the first file.
const file = requestedFileId === undefined
? transfer.files[0]
: transfer.files.find((f) => f.id === requestedFileId)
if (!file) {
return NextResponse.json({ error: 'File not found in this transfer' }, { status: 404 })
}
try {
await fs.access(file.path)
@@ -103,9 +131,9 @@ export async function POST(
try {
const first = await frames.next()
if (!first.done) firstFrame = first.value
} catch (err: any) {
} catch (err: unknown) {
await frames.return(undefined as never).catch(() => {})
if (err?.message === 'UNSUPPORTED_FORMAT') {
if (err instanceof Error && err.message === 'UNSUPPORTED_FORMAT') {
console.error(`Legacy-format file for transfer ${transfer.id}: ${file.path}`)
return NextResponse.json(
{ error: 'This transfer was created with an older, incompatible version and cannot be decrypted. Please ask the sender to resend it.' },
+19
View File
@@ -3,6 +3,11 @@ import { prisma } from '@/lib/prisma'
import { NextResponse } from 'next/server'
import bcrypt from 'bcrypt'
import { TransferStatus } from '@prisma/client'
import { rateLimit, resetRateLimit, clientKey } from '@/lib/rate-limit'
// 10 password attempts per transfer, per client, per 15 minutes.
const ATTEMPT_LIMIT = 10
const ATTEMPT_WINDOW_MS = 15 * 60 * 1000
export async function POST(req: Request) {
const { id, password } = await req.json()
@@ -11,6 +16,17 @@ export async function POST(req: Request) {
return NextResponse.json({ success: false, message: 'Missing ID or password' }, { status: 400 })
}
// Keyed before the DB lookup so throttling costs an attacker a request
// regardless of whether the transfer exists.
const key = `verify:${id}:${clientKey(req.headers)}`
const limit = rateLimit(key, ATTEMPT_LIMIT, ATTEMPT_WINDOW_MS)
if (!limit.allowed) {
return NextResponse.json(
{ success: false, message: 'Too many attempts. Please try again later.' },
{ status: 429, headers: { 'Retry-After': String(limit.retryAfter) } }
)
}
const transfer = await prisma.transfer.findUnique({
where: { downloadUrl: id },
include: { files: true },
@@ -39,6 +55,9 @@ export async function POST(req: Request) {
return NextResponse.json({ success: false, message: 'Incorrect password' }, { status: 401 })
}
// Correct password: clear the counter so an earlier typo does not throttle.
resetRateLimit(key)
// Explicit allow-list rather than spreading the row: `files` carries absolute
// server paths, and the row carries passwordHash and the owning userId.
const totalSize = transfer.files.reduce((sum, file) => sum + file.size, BigInt(0))
+4 -2
View File
@@ -1,7 +1,7 @@
'use client';
import { useState } from 'react';
import { signIn, getSession } from 'next-auth/react';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
@@ -52,6 +52,7 @@ export default function SignInPage() {
router.push('/');
}
} catch (error) {
console.error(error);
toast.error('Something went wrong');
} finally {
setIsLoading(false);
@@ -63,6 +64,7 @@ export default function SignInPage() {
try {
await signIn(provider, { callbackUrl: '/send' });
} catch (error) {
console.error(error);
toast.error(`Failed to sign in with ${provider}`);
setLoadingProvider(null);
}
@@ -213,7 +215,7 @@ export default function SignInPage() {
<div className="text-center">
<p className="text-sm text-slate-600 dark:text-slate-400">
Don't have an account?{' '}
Don&apos;t have an account?{' '}
<Link
href="/auth/signup"
className="text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 font-medium"
+2
View File
@@ -80,6 +80,7 @@ export default function SignUpPage() {
router.push('/');
}
} catch (error) {
console.error(error);
toast.error('Something went wrong');
} finally {
setIsLoading(false);
@@ -91,6 +92,7 @@ export default function SignUpPage() {
try {
await signIn(provider, { callbackUrl: '/' });
} catch (error) {
console.error(error);
toast.error(`Failed to sign up with ${provider}`);
setLoadingProvider(null);
}
+107 -40
View File
@@ -2,7 +2,6 @@
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { decryptBlob } from '@/lib/encryption';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
@@ -18,44 +17,55 @@ import { Badge } from '@/components/ui/badge';
import {
Download,
File,
FileText,
Image,
Music,
Video,
Archive,
Clock,
Shield,
User,
MessageSquare,
CheckCircle,
Lock,
Eye,
EyeOff,
AlertCircle,
Mail,
HardDrive,
} from 'lucide-react';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { formatFileSize, formatTimeRemaining } from '@/lib/utils';
import { saveResponseToDisk, DownloadCancelled } from '@/lib/download';
interface TransferFile {
id: number;
name: string;
size: number;
}
interface TransferInfo {
senderEmail: string;
expiresAt: string;
// Pre-authentication shape
fileCount?: number;
totalSize: number;
requiresPassword?: boolean;
// Post-verification shape
message?: string | null;
totalFiles?: number;
files?: TransferFile[];
}
export default function DownloadPage() {
const { id } = useParams() as { id: string };
const [transfer, setTransfer] = useState<any>(null);
const [transfer, setTransfer] = useState<TransferInfo | null>(null);
const [password, setPassword] = useState('');
const [status, setStatus] = useState('');
const [downloading, setDownloading] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [passwordError, setPasswordError] = useState('');
const [isVerifying, setIsVerifying] = useState(false);
const [downloadingFiles, setDownloadingFiles] = useState<Set<string>>(
const [downloadingFiles, setDownloadingFiles] = useState<Set<number>>(
new Set()
);
const [downloadingAll, setDownloadingAll] = useState(false);
const [downloadedFiles, setDownloadedFiles] = useState<Set<string>>(
const [downloadedFiles, setDownloadedFiles] = useState<Set<number>>(
new Set()
);
@@ -82,18 +92,17 @@ export default function DownloadPage() {
loadTransfer();
}, [id]);
const handleDecrypt = async () => {
try {
setDownloading(true);
setDownloadingAll(true);
setStatus('Downloading and decrypting file...');
const downloadFile = async (file: TransferFile) => {
setDownloadingFiles((prev) => new Set(prev).add(file.id));
setStatus(`Downloading ${file.name}...`);
try {
// POST so the password stays out of the URL (and therefore out of access
// logs and Referer headers).
const res = await fetch(`/api/file/${encodeURIComponent(id)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
body: JSON.stringify({ password, fileId: file.id }),
});
if (!res.ok) {
@@ -101,22 +110,42 @@ export default function DownloadPage() {
throw new Error(err?.error || 'File not found or invalid password.');
}
const decryptedBlob = await res.blob();
const url = URL.createObjectURL(decryptedBlob);
const a = document.createElement('a');
a.href = url;
a.download = transfer.files?.[0]?.name?.replace(/\.enc$/, '') || 'file';
a.click();
URL.revokeObjectURL(url);
// Streams straight to disk where supported, so a multi-GB file is never
// held in browser memory.
await saveResponseToDisk(res, file.name.replace(/\.enc$/, '') || 'file');
setStatus('Download complete!');
} catch (err: any) {
setDownloadedFiles((prev) => new Set(prev).add(file.id));
setStatus('');
toast.success(`${file.name} downloaded`);
} catch (err: unknown) {
if (err instanceof DownloadCancelled) {
setStatus('');
return;
}
console.error(err);
setStatus('Download failed: ' + err.message);
const detail = err instanceof Error ? err.message : String(err);
setStatus(`Download failed: ${detail}`);
toast.error(detail);
} finally {
setDownloadingFiles((prev) => {
const next = new Set(prev);
next.delete(file.id);
return next;
});
}
};
const handleDecrypt = async () => {
if (!transfer?.files?.length) return;
setDownloadingAll(true);
try {
// Sequential: parallel downloads of multi-GB files would compete for
// bandwidth and memory, and each needs its own save prompt anyway.
for (const file of transfer.files) {
await downloadFile(file);
}
} finally {
setDownloading(false);
setDownloadingAll(false);
setDownloadedFiles(new Set(transfer.files.map((f: any) => f.id)));
}
};
@@ -151,8 +180,8 @@ export default function DownloadPage() {
}
};
const isFileDownloading = (fileId: string) => downloadingFiles.has(fileId);
const isFileDownloaded = (fileId: string) => downloadedFiles.has(fileId);
const isFileDownloading = (fileId: number) => downloadingFiles.has(fileId);
const isFileDownloaded = (fileId: number) => downloadedFiles.has(fileId);
if (!transfer) {
return (
@@ -362,7 +391,7 @@ export default function DownloadPage() {
<div className="flex items-start justify-between">
<div className="flex-1">
<CardTitle className="text-xl mb-2 text-white">
Transfer from {transfer.senderName}
Transfer from {transfer.senderEmail}
</CardTitle>
<CardDescription className="text-base">
<div className="flex items-center gap-2 mb-1 text-gray-400">
@@ -398,7 +427,10 @@ export default function DownloadPage() {
<div className="flex flex-wrap items-center gap-6 text-sm text-gray-400">
<div className="flex items-center gap-2">
<File className="h-4 w-4" />
<span>{transfer.files.length} files</span>
<span>
{transfer.files?.length ?? 0}{' '}
{transfer.files?.length === 1 ? 'file' : 'files'}
</span>
</div>
<div className="flex items-center gap-2">
<Download className="h-4 w-4" />
@@ -406,7 +438,9 @@ export default function DownloadPage() {
</div>
<div className="flex items-center gap-2">
<Clock className="h-4 w-4" />
<span>Expires {transfer.expiresAt}</span>
<span>
Expires {formatTimeRemaining(new Date(transfer.expiresAt))}
</span>
</div>
</div>
</CardContent>
@@ -441,18 +475,51 @@ export default function DownloadPage() {
<h2 className="text-lg font-semibold text-white mb-4">
Files in this transfer
</h2>
{transfer.filenames?.map((name: string, index: number) => (
{transfer.files?.map((file) => (
<Card
key={index}
key={file.id}
className="border-gray-800 bg-gray-900/60 backdrop-blur-xl hover:bg-gray-900/80 transition-all duration-200"
>
<CardContent>
<h3 className="font-medium text-white truncate">{name}</h3>
<CardContent className="flex items-center justify-between gap-4 py-4">
<div className="min-w-0">
<h3 className="font-medium text-white truncate">{file.name}</h3>
<p className="text-sm text-gray-400">
{formatFileSize(file.size)}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => downloadFile(file)}
disabled={isFileDownloading(file.id) || downloadingAll}
className="shrink-0"
>
{isFileDownloading(file.id) ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-2 border-current border-t-transparent mr-2" />
Downloading
</>
) : isFileDownloaded(file.id) ? (
<>
<Download className="h-4 w-4 mr-2" />
Download again
</>
) : (
<>
<Download className="h-4 w-4 mr-2" />
Download
</>
)}
</Button>
</CardContent>
</Card>
))}
</div>
{status && (
<p className="mt-4 text-sm text-gray-400 text-center">{status}</p>
)}
{/* Footer */}
<div className="mt-12 text-center">
<div className="inline-flex items-center gap-2 text-sm text-gray-500 mb-4">
+9 -14
View File
@@ -8,17 +8,12 @@ import { HeroSection } from '@/components/hero-section';
import { Stats } from '@/components/stats';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
ArrowRight,
Shield,
Zap,
Globe,
Mail,
Lock,
Clock,
Users,
Star,
CheckCircle
import {
ArrowRight,
Shield,
Zap,
Mail,
Star
} from 'lucide-react';
import Link from 'next/link';
@@ -186,7 +181,7 @@ export default function Home() {
))}
</div>
<p className="text-slate-600 dark:text-slate-400 mb-4">
"Transfer Tribe has revolutionized how we share large design files with clients. The security features give us peace of mind."
&ldquo;Transfer Tribe has revolutionized how we share large design files with clients. The security features give us peace of mind.&rdquo;
</p>
<div className="flex items-center space-x-3">
<div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full flex items-center justify-center text-white font-semibold">
@@ -208,7 +203,7 @@ export default function Home() {
))}
</div>
<p className="text-slate-600 dark:text-slate-400 mb-4">
"Simple, fast, and secure. Exactly what we needed for sharing confidential documents with our legal team."
&ldquo;Simple, fast, and secure. Exactly what we needed for sharing confidential documents with our legal team.&rdquo;
</p>
<div className="flex items-center space-x-3">
<div className="w-10 h-10 bg-gradient-to-br from-green-500 to-emerald-600 rounded-full flex items-center justify-center text-white font-semibold">
@@ -230,7 +225,7 @@ export default function Home() {
))}
</div>
<p className="text-slate-600 dark:text-slate-400 mb-4">
"The email integration is brilliant. Our clients love how easy it is to receive and download files."
&ldquo;The email integration is brilliant. Our clients love how easy it is to receive and download files.&rdquo;
</p>
<div className="flex items-center space-x-3">
<div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-pink-600 rounded-full flex items-center justify-center text-white font-semibold">
+4 -7
View File
@@ -12,12 +12,9 @@ import {
Crown,
Gift,
Upload,
Clock,
Shield,
Users,
Mail,
Settings,
Infinity
Mail
} from 'lucide-react';
interface PricingTier {
@@ -25,7 +22,7 @@ interface PricingTier {
price: string;
period: string;
description: string;
icon: React.ComponentType<any>;
icon: React.ComponentType<{ className?: string }>;
popular?: boolean;
features: {
name: string;
@@ -147,7 +144,7 @@ export default function PricingPage() {
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 max-w-7xl mx-auto">
{tiers.map((tier, index) => {
{tiers.map((tier) => {
const IconComponent = tier.icon;
return (
<Card
@@ -198,7 +195,7 @@ export default function PricingPage() {
<div className="space-y-4">
<h4 className="font-semibold text-slate-900 dark:text-slate-100">
What's included:
What&apos;s included:
</h4>
<ul className="space-y-3">
{tier.features.map((feature, featureIndex) => (
+2 -9
View File
@@ -5,15 +5,13 @@ import { useEffect, useState } from 'react';
import { Header } from '@/components/header';
import SendPage from '@/components/send-transfer-server-encrypted';
import { MyTransfers } from '@/components/my-transfers';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
Upload,
Send,
History,
Files,
TrendingUp,
Download,
Clock,
Shield,
@@ -23,14 +21,9 @@ export default function DashboardPage() {
const [activeTab, setActiveTab] = useState<'send' | 'transfers' | 'files'>(
'send'
);
const [userFiles, setUserFiles] = useState<any[]>([]);
const { data: session, status } = useSession();
const { data: session } = useSession();
const userName = session?.user?.name || 'friend';
const handleFileUpload = (files: any[]) => {
setUserFiles((prev) => [...prev, ...files]);
};
const [stats, setStats] = useState({
transfersSent: 0,
downloads: 0,
+1 -1
View File
@@ -1,5 +1,5 @@
import { Button } from '@/components/ui/button';
import { ArrowRight, Shield, Zap, Globe, Mail, Lock, Clock } from 'lucide-react';
import { ArrowRight, Mail, Lock, Clock } from 'lucide-react';
export function HeroSection() {
return (
+10 -8
View File
@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -12,7 +12,6 @@ import {
Share2,
Trash2,
File,
Mail,
Clock,
Users,
MoreVertical,
@@ -64,7 +63,7 @@ export function MyTransfers() {
)
);
const fetchTransfers = async () => {
const fetchTransfers = useCallback(async () => {
if (!session?.user?.email) return;
setIsLoading(true);
@@ -78,15 +77,16 @@ export function MyTransfers() {
toast.error('Failed to fetch transfers');
}
} catch (error) {
console.error(error);
toast.error('Failed to fetch transfers');
} finally {
setIsLoading(false);
}
};
}, [session?.user?.email]);
useEffect(() => {
fetchTransfers();
}, [session]);
}, [fetchTransfers]);
const handleResend = async (transferId: number) => {
try {
@@ -100,6 +100,7 @@ export function MyTransfers() {
toast.error('Failed to resend transfer');
}
} catch (error) {
console.error(error);
toast.error('Failed to resend transfer');
}
};
@@ -117,6 +118,7 @@ export function MyTransfers() {
toast.error('Failed to delete transfer');
}
} catch (error) {
console.error(error);
toast.error('Failed to delete transfer');
}
};
@@ -184,7 +186,7 @@ const copyShareLink = (transferId: number) => {
No transfers found
</h3>
<p className="text-slate-500 dark:text-slate-400">
You haven't sent any transfers yet
You haven&apos;t sent any transfers yet
</p>
</div>
)}
@@ -273,7 +275,7 @@ const copyShareLink = (transferId: number) => {
{transfer.message && (
<div className="bg-slate-50 dark:bg-slate-800/50 rounded-lg p-3 mb-4">
<p className="text-sm text-slate-600 dark:text-slate-400">
"{transfer.message}"
&ldquo;{transfer.message}&rdquo;
</p>
</div>
)}
@@ -307,7 +309,7 @@ const copyShareLink = (transferId: number) => {
{filteredTransfers.length === 0 && searchTerm && transfers.length > 0 && (
<div className="text-center py-8">
<p className="text-slate-500 dark:text-slate-400">
No transfers found matching "{searchTerm}"
No transfers found matching &ldquo;{searchTerm}&rdquo;
</p>
</div>
)}
-428
View File
@@ -1,428 +0,0 @@
'use client';
import { useSession } from 'next-auth/react';
import { useState, useEffect, useRef } from 'react';
import { encryptBlob } from '@/lib/encryption';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Upload, File, X, Send } from 'lucide-react';
import { toast } from 'sonner';
import { formatFileSize } from '@/lib/utils';
import { Loader2 } from 'lucide-react';
const PLAN_LIMITS = {
free: {
maxFileSizeMB: 2048,
maxMonthlyTransferSizeMB: 10240,
expiryText: '48 hours after sending',
},
rookie: {
maxFileSizeMB: Infinity,
maxMonthlyTransferSizeMB: 30720,
expiryText: '7 days after sending',
},
pro: {
maxFileSizeMB: Infinity,
maxMonthlyTransferSizeMB: 1024 * 1024,
expiryText: '30 days after sending',
},
};
const CHUNK_SIZE = 10 * 1024 * 1024; // 10MB chunks
export default function SendPage() {
const { data: session } = useSession();
const [files, setFiles] = useState<File[]>([]);
const [recipient, setRecipient] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const [plan, setPlan] = useState<'free' | 'rookie' | 'pro'>('free');
const [remainingMB, setRemainingMB] = useState(Infinity);
const [usedMB, setUsedMB] = useState(0);
const [uploadProgress, setUploadProgress] = useState(0);
const [uploadStep, setUploadStep] = useState('');
const [uploadMessage, setUploadMessage] = useState('');
const [currentChunk, setCurrentChunk] = useState(0);
const [totalChunks, setTotalChunks] = useState(0);
const dropRef = useRef<HTMLDivElement>(null);
const totalSize = files.reduce((acc, file) => acc + file.size, 0);
const totalSizeMB = totalSize / 1024 / 1024;
const isOverLimit =
totalSizeMB > PLAN_LIMITS[plan].maxFileSizeMB || totalSizeMB > remainingMB;
useEffect(() => {
const fetchPlan = async () => {
const res = await fetch('/api/usage');
if (res.ok) {
const data = await res.json();
setPlan(data.plan);
setRemainingMB(data.remainingMB);
setUsedMB(data.usedMB);
}
};
if (session?.user?.email) fetchPlan();
}, [session]);
const handleFileAdd = (newFiles: File[]) => {
const unique = newFiles.filter(
(newFile) =>
!files.find(
(existing) =>
existing.name === newFile.name && existing.size === newFile.size
)
);
setFiles((prev) => [...prev, ...unique]);
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return;
handleFileAdd(Array.from(e.target.files));
};
const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
if (e.dataTransfer.files) {
handleFileAdd(Array.from(e.dataTransfer.files));
}
dropRef.current?.classList.remove('border-blue-500');
};
const removeFile = (index: number) => {
setFiles((prev) => prev.filter((_, i) => i !== index));
};
const fileInputRef = useRef<HTMLInputElement>(null);
const triggerFileInput = () => fileInputRef.current?.click();
const handleSubmit = async () => {
if (!files.length)
return setUploadMessage('Please select at least one file');
if (!recipient || !password)
return setUploadMessage('All fields are required');
if (isOverLimit)
return setUploadMessage('File size exceeds your plan limits');
const senderEmail = session?.user?.email;
if (!senderEmail)
return setUploadMessage('Unable to get sender email. Please log in.');
try {
setUploadStep('Preparing files');
const file = files[0]; // Upload first file for now
setUploadStep('Encrypting');
// Encrypt the file using the password
const { encryptedBlob } = await encryptBlob(file, password);
// Convert blob to Uint8Array once to avoid multiple arrayBuffer() calls
// (which can cause "NotReadableError" on some browsers)
const encryptedBytes = new Uint8Array(await encryptedBlob.arrayBuffer());
const iv = encryptedBytes.slice(0, 12);
const ivBase64 = btoa(String.fromCharCode(...iv));
// Calculate chunks
const CHUNK_SIZE_BYTES = CHUNK_SIZE;
const totalChunksCount = Math.ceil(encryptedBytes.length / CHUNK_SIZE_BYTES);
setTotalChunks(totalChunksCount);
// Generate upload ID
const uploadId = crypto.randomUUID();
// Upload chunks
setUploadStep('Uploading');
for (let i = 0; i < totalChunksCount; i++) {
setCurrentChunk(i + 1);
const start = i * CHUNK_SIZE_BYTES;
const end = Math.min(start + CHUNK_SIZE_BYTES, encryptedBytes.length);
const chunkBytes = encryptedBytes.slice(start, end);
const chunkBlob = new Blob([chunkBytes]);
const formData = new FormData();
formData.append('chunk', chunkBlob);
formData.append('uploadId', uploadId);
formData.append('chunkIndex', i.toString());
formData.append('totalChunks', totalChunksCount.toString());
formData.append('chunkSize', CHUNK_SIZE_BYTES.toString());
// Only send metadata on first chunk
if (i === 0) {
formData.append('email', recipient);
formData.append('password', password);
formData.append('sender', senderEmail);
formData.append('originalFilename', file.name);
formData.append('encryptionIv', ivBase64);
const filenames = files.map((f) => f.name);
formData.append('filenames', JSON.stringify(filenames));
formData.append('message', message);
}
const uploadRes = await fetch('/api/chunk-upload', {
method: 'POST',
body: formData,
});
if (!uploadRes.ok) {
const error = await uploadRes.json();
throw new Error(error.message || `Chunk ${i} upload failed`);
}
// Update progress
const chunkProgress = ((i + 1) / totalChunksCount) * 100;
setUploadProgress(Math.round(chunkProgress));
}
// Finalize upload
setUploadStep('Finalizing');
const finalRes = await fetch(`/api/chunk-upload?uploadId=${uploadId}`, {
method: 'PUT',
});
if (!finalRes.ok) {
const error = await finalRes.json();
throw new Error(error.message || 'Failed to finalize upload');
}
const result = await finalRes.json();
setUploadStep('');
setUploadMessage('Success! 🎉');
toast.success('Your transfer has been sent successfully!');
setFiles([]);
setRecipient('');
setPassword('');
setUploadProgress(100);
setTimeout(() => setUploadMessage(''), 3000);
} catch (err: any) {
console.error(err);
setUploadStep('');
setUploadMessage('Error: ' + err.message);
}
};
function UploadStatusToast({
step,
progress,
message,
currentChunk,
totalChunks,
}: {
step: string;
progress: number;
message: string;
currentChunk: number;
totalChunks: number;
}) {
const showSpinner = ['Encrypting', 'Uploading', 'Finalizing'].includes(step);
const isError =
message.toLowerCase().includes('error') || message.includes('fail');
if (!step && !message) return null;
return (
<div className="w-full p-4 bg-slate-100 dark:bg-slate-800 rounded-lg shadow-md flex flex-col space-y-2">
<div className="flex items-center gap-2">
{showSpinner && (
<Loader2 className="h-4 w-4 animate-spin text-blue-600" />
)}
<p
className={`text-sm font-medium ${
isError ? 'text-red-600' : 'text-slate-800 dark:text-slate-100'
}`}
>
{step}{currentChunk && totalChunks ? ` (${currentChunk}/${totalChunks})` : ''}
</p>
</div>
{!isError && step === 'Uploading' && (
<>
<Progress value={progress} className="h-2" />
<p className="text-xs text-red-600 font-medium">
Please do not close this page during upload!
</p>
</>
)}
</div>
);
}
return (
<div className="space-y-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* File Upload Section */}
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
Upload Files
</h3>
<div
ref={dropRef}
onDrop={handleDrop}
onDragOver={(e) => {
e.preventDefault();
dropRef.current?.classList.add('border-blue-500');
}}
onDragLeave={() =>
dropRef.current?.classList.remove('border-blue-500')
}
className="border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all"
>
<div className="flex flex-col items-center space-y-4">
<div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full flex items-center justify-center">
<Upload className="w-8 h-8 text-white" />
</div>
<div>
<p className="text-lg font-semibold text-slate-900 dark:text-slate-100">
Drag & drop files here
</p>
<p className="text-sm text-slate-500 dark:text-slate-400">
or click to select files
</p>
</div>
<Button
variant="outline"
type="button"
onClick={triggerFileInput}
>
Select Files
</Button>
<input
ref={fileInputRef}
type="file"
multiple
onChange={handleFileChange}
className="hidden"
/>
</div>
</div>
{/* Files List */}
{files.length > 0 && (
<div className="mt-6 space-y-2">
<h4 className="font-semibold text-slate-900 dark:text-slate-100">
Selected Files ({files.length})
</h4>
<div className="space-y-2 max-h-40 overflow-y-auto">
{files.map((file, i) => (
<div
key={i}
className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-900 rounded-lg"
>
<div className="flex items-center gap-2 flex-1 min-w-0">
<File className="w-4 h-4 flex-shrink-0 text-slate-500" />
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
{file.name}
</p>
<p className="text-xs text-slate-500">
{formatFileSize(file.size)}
</p>
</div>
</div>
<button
onClick={() => removeFile(i)}
className="p-1 hover:bg-slate-200 dark:hover:bg-slate-800 rounded"
>
<X className="w-4 h-4 text-slate-500" />
</button>
</div>
))}
</div>
</div>
)}
{/* Size Info */}
<div className="mt-4 text-sm text-slate-600 dark:text-slate-400">
<p>Total Size: {formatFileSize(totalSize)}</p>
{remainingMB !== Infinity && (
<p>Remaining: {remainingMB.toFixed(2)} MB</p>
)}
</div>
</div>
</div>
{/* Transfer Details Section */}
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
Transfer Details
</h3>
<Card>
<CardContent className="pt-6 space-y-4">
<div>
<Label htmlFor="recipient" className="text-slate-700 dark:text-slate-300">
Recipient Email
</Label>
<Input
id="recipient"
type="email"
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
placeholder="recipient@example.com"
className="mt-1"
/>
</div>
<div>
<Label htmlFor="password" className="text-slate-700 dark:text-slate-300">
Encryption Password
</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Create a strong password"
className="mt-1"
/>
</div>
<div>
<Label htmlFor="message" className="text-slate-700 dark:text-slate-300">
Message (optional)
</Label>
<Textarea
id="message"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Add a message to your recipient..."
className="mt-1 resize-none"
rows={4}
/>
</div>
{isOverLimit && (
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded text-red-700 dark:text-red-400 text-sm">
File size exceeds your plan limits
</div>
)}
<Button
onClick={handleSubmit}
disabled={!files.length || isOverLimit || uploadStep !== ''}
className="w-full"
>
<Send className="w-4 h-4 mr-2" />
Send Transfer
</Button>
{uploadMessage && (
<UploadStatusToast
step={uploadStep}
progress={uploadProgress}
message={uploadMessage}
currentChunk={currentChunk}
totalChunks={totalChunks}
/>
)}
</CardContent>
</Card>
</div>
</div>
</div>
</div>
);
}
@@ -41,7 +41,6 @@ export default function SendPage() {
const [message, setMessage] = useState('');
const [plan, setPlan] = useState<'free' | 'rookie' | 'pro'>('free');
const [remainingMB, setRemainingMB] = useState(Infinity);
const [usedMB, setUsedMB] = useState(0);
const [uploadProgress, setUploadProgress] = useState(0);
const [uploadStep, setUploadStep] = useState('');
const [uploadMessage, setUploadMessage] = useState('');
@@ -60,7 +59,6 @@ export default function SendPage() {
const data = await res.json();
setPlan(data.plan);
setRemainingMB(data.remainingMB);
setUsedMB(data.usedMB);
}
};
if (session?.user?.email) fetchPlan();
@@ -111,10 +109,11 @@ export default function SendPage() {
try {
setUploadStep('Preparing files');
const file = files[0]; // Upload first file for now
// Calculate chunks from raw file (no encryption)
const totalChunksCount = Math.ceil(file.size / CHUNK_SIZE);
// Chunk counts for every selected file, so progress spans the whole
// transfer rather than just the first file.
const perFileChunks = files.map((f) => Math.max(1, Math.ceil(f.size / CHUNK_SIZE)));
const totalChunksCount = perFileChunks.reduce((a, b) => a + b, 0);
setTotalChunks(totalChunksCount);
// Generate upload ID
@@ -122,44 +121,48 @@ export default function SendPage() {
// Upload raw chunks - server will encrypt each chunk
setUploadStep('Uploading');
for (let i = 0; i < totalChunksCount; i++) {
setCurrentChunk(i + 1);
const start = i * CHUNK_SIZE;
const end = Math.min(start + CHUNK_SIZE, file.size);
const chunkFile = file.slice(start, end);
let uploadedChunks = 0;
const formData = new FormData();
formData.append('chunk', chunkFile);
formData.append('uploadId', uploadId);
formData.append('chunkIndex', i.toString());
formData.append('totalChunks', totalChunksCount.toString());
formData.append('chunkSize', CHUNK_SIZE.toString());
// Only send metadata on first chunk
if (i === 0) {
formData.append('email', recipient);
formData.append('password', password);
formData.append('sender', senderEmail);
formData.append('originalFilename', file.name);
const filenames = files.map((f) => f.name);
formData.append('filenames', JSON.stringify(filenames));
formData.append('message', message);
for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
const file = files[fileIndex];
const fileChunks = perFileChunks[fileIndex];
for (let i = 0; i < fileChunks; i++) {
const start = i * CHUNK_SIZE;
const end = Math.min(start + CHUNK_SIZE, file.size);
const chunkFile = file.slice(start, end);
const formData = new FormData();
formData.append('chunk', chunkFile);
formData.append('uploadId', uploadId);
formData.append('fileIndex', fileIndex.toString());
formData.append('chunkIndex', i.toString());
formData.append('fileChunks', fileChunks.toString());
formData.append('fileCount', files.length.toString());
formData.append('fileName', file.name);
// Transfer-wide metadata travels with the very first chunk only.
if (fileIndex === 0 && i === 0) {
formData.append('email', recipient);
formData.append('password', password);
formData.append('filenames', JSON.stringify(files.map((f) => f.name)));
formData.append('message', message);
}
const uploadRes = await fetch('/api/chunk-upload-v2', {
method: 'POST',
body: formData,
});
if (!uploadRes.ok) {
const error = await uploadRes.json().catch(() => ({}));
throw new Error(error.message || `Chunk ${i} of ${file.name} failed`);
}
uploadedChunks++;
setCurrentChunk(uploadedChunks);
setUploadProgress(Math.round((uploadedChunks / totalChunksCount) * 100));
}
const uploadRes = await fetch('/api/chunk-upload-v2', {
method: 'POST',
body: formData,
});
if (!uploadRes.ok) {
const error = await uploadRes.json();
throw new Error(error.message || `Chunk ${i} upload failed`);
}
// Update progress
const chunkProgress = ((i + 1) / totalChunksCount) * 100;
setUploadProgress(Math.round(chunkProgress));
}
// Finalize upload
@@ -169,24 +172,23 @@ export default function SendPage() {
});
if (!finalRes.ok) {
const error = await finalRes.json();
const error = await finalRes.json().catch(() => ({}));
throw new Error(error.message || 'Failed to finalize upload');
}
const result = await finalRes.json();
setUploadStep('');
setUploadMessage('Success! 🎉');
toast.success('Your transfer has been sent successfully!');
setFiles([]);
setRecipient('');
setPassword('');
setMessage('');
setUploadProgress(100);
setTimeout(() => setUploadMessage(''), 3000);
} catch (err: any) {
} catch (err: unknown) {
console.error(err);
setUploadStep('');
setUploadMessage('Error: ' + err.message);
setUploadMessage('Error: ' + (err instanceof Error ? err.message : String(err)));
}
};
-425
View File
@@ -1,425 +0,0 @@
'use client';
import { useSession } from 'next-auth/react';
import { useState, useEffect, useRef } from 'react';
import { encryptBlob } from '@/lib/encryption';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Upload, File, X, Send } from 'lucide-react';
import { toast } from 'sonner';
import { formatFileSize } from '@/lib/utils';
import { Loader2 } from 'lucide-react';
const PLAN_LIMITS = {
free: {
maxFileSizeMB: 2048,
maxMonthlyTransferSizeMB: 10240,
expiryText: '48 hours after sending',
},
rookie: {
maxFileSizeMB: Infinity,
maxMonthlyTransferSizeMB: 30720,
expiryText: '7 days after sending',
},
pro: {
maxFileSizeMB: Infinity,
maxMonthlyTransferSizeMB: 1024 * 1024,
expiryText: '30 days after sending',
},
};
export default function SendPage() {
const { data: session } = useSession();
const [files, setFiles] = useState<File[]>([]);
const [recipient, setRecipient] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const [plan, setPlan] = useState<'free' | 'rookie' | 'pro'>('free');
const [remainingMB, setRemainingMB] = useState(Infinity);
const [usedMB, setUsedMB] = useState(0);
const [uploadProgress, setUploadProgress] = useState(0);
const [uploadStep, setUploadStep] = useState('');
const [uploadMessage, setUploadMessage] = useState('');
const dropRef = useRef<HTMLDivElement>(null);
const totalSize = files.reduce((acc, file) => acc + file.size, 0);
const totalSizeMB = totalSize / 1024 / 1024;
const isOverLimit =
totalSizeMB > PLAN_LIMITS[plan].maxFileSizeMB || totalSizeMB > remainingMB;
useEffect(() => {
const fetchPlan = async () => {
const res = await fetch('/api/usage');
if (res.ok) {
const data = await res.json();
setPlan(data.plan);
setRemainingMB(data.remainingMB);
setUsedMB(data.usedMB);
}
};
if (session?.user?.email) fetchPlan();
}, [session]);
const handleFileAdd = (newFiles: File[]) => {
const unique = newFiles.filter(
(newFile) =>
!files.find(
(existing) =>
existing.name === newFile.name && existing.size === newFile.size
)
);
setFiles((prev) => [...prev, ...unique]);
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return;
handleFileAdd(Array.from(e.target.files));
};
const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
if (e.dataTransfer.files) {
handleFileAdd(Array.from(e.dataTransfer.files));
}
dropRef.current?.classList.remove('border-blue-500');
};
const removeFile = (index: number) => {
setFiles((prev) => prev.filter((_, i) => i !== index));
};
const fileInputRef = useRef<HTMLInputElement>(null);
const triggerFileInput = () => fileInputRef.current?.click();
const handleSubmit = async () => {
if (!files.length)
return setUploadMessage('Please select at least one file');
if (!recipient || !password)
return setUploadMessage('All fields are required');
if (isOverLimit)
return setUploadMessage('File size exceeds your plan limits');
const senderEmail = session?.user?.email;
if (!senderEmail)
return setUploadMessage('Unable to get sender email. Please log in.');
try {
setUploadStep('Preparing files');
const file = files[0]; // Upload first file for now
setUploadStep('Encrypting');
// Encrypt the file using the password
const { encryptedBlob } = await encryptBlob(file, password);
// Extract IV from encrypted blob (first 12 bytes)
const encryptedBytes = new Uint8Array(await encryptedBlob.arrayBuffer());
const iv = encryptedBytes.slice(0, 12);
const ivBase64 = btoa(String.fromCharCode(...iv));
const formData = new FormData();
formData.append('file', encryptedBlob, file.name + '.enc');
formData.append('email', recipient);
formData.append('password', password);
formData.append('sender', senderEmail);
formData.append('originalFilename', file.name);
formData.append('encryptionIv', ivBase64);
const filenames = files.map((f) => f.name);
formData.append('filenames', JSON.stringify(filenames));
formData.append('message', message);
setUploadProgress(0);
setUploadStep('Uploading');
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/send');
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
setUploadProgress(percent);
}
};
xhr.onload = () => {
if (xhr.status === 200) {
setUploadStep('');
setUploadMessage('Success! 🎉');
toast.success('Your transfer has been sent successfully!');
setFiles([]);
setRecipient('');
setPassword('');
setUploadProgress(100);
setTimeout(() => setUploadMessage(''), 3000);
} else {
setUploadStep('');
setUploadMessage(`Upload failed: ${xhr.statusText}`);
}
};
xhr.onerror = () => {
setUploadStep('');
setUploadMessage('Upload error occurred');
};
xhr.send(formData);
} catch (err: any) {
console.error(err);
setUploadStep('');
setUploadMessage('Error: ' + err.message);
}
};
function UploadStatusToast({
step,
progress,
message,
}: {
step: string;
progress: number;
message: string;
}) {
const showSpinner = ['Zipping', 'Encrypting', 'Uploading'].includes(step);
const isError =
message.toLowerCase().includes('error') || message.includes('fail');
if (!step && !message) return null;
return (
<div className="w-full p-4 bg-slate-100 dark:bg-slate-800 rounded-lg shadow-md flex flex-col space-y-2">
<div className="flex items-center gap-2">
{showSpinner && (
<Loader2 className="h-4 w-4 animate-spin text-blue-600" />
)}
<p
className={`text-sm font-medium ${
isError ? 'text-red-600' : 'text-slate-800 dark:text-slate-100'
}`}
>
{step || message}
</p>
</div>
{!isError && step === 'Uploading' && (
<>
<Progress value={progress} className="h-2" />
<p className="text-xs text-red-600 font-medium">
Please do not close this page during upload!
</p>
</>
)}
</div>
);
}
return (
<div className="space-y-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* File Upload Section */}
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
Upload Files
</h3>
<div
ref={dropRef}
onDrop={handleDrop}
onDragOver={(e) => {
e.preventDefault();
dropRef.current?.classList.add('border-blue-500');
}}
onDragLeave={() =>
dropRef.current?.classList.remove('border-blue-500')
}
className="border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all"
>
<div className="flex flex-col items-center space-y-4">
<div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full flex items-center justify-center">
<Upload className="w-8 h-8 text-white" />
</div>
<div>
<p className="text-lg font-semibold text-slate-900 dark:text-slate-100">
Drag & drop files here
</p>
<p className="text-sm text-slate-500 dark:text-slate-400">
or click to select files (max 2GB)
</p>
</div>
<Button
variant="outline"
type="button"
onClick={triggerFileInput}
>
Select Files
</Button>
<input
ref={fileInputRef}
id="file-upload"
type="file"
multiple
className="hidden"
onChange={handleFileChange}
/>
</div>
</div>
{files.length > 0 && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h4 className="font-semibold text-slate-900 dark:text-slate-100">
Files ({files.length})
</h4>
<div className="text-sm text-slate-500 dark:text-slate-400">
<span>Total: {formatFileSize(totalSize)}</span>
</div>
</div>
<div className="space-y-3 max-h-64 overflow-y-auto">
{files.map((file, idx) => (
<Card
key={idx}
className="bg-white/60 dark:bg-slate-800/60 backdrop-blur-sm border-white/20 dark:border-slate-700/20"
>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3 flex-1 min-w-0">
<div className="w-10 h-10 bg-slate-100 dark:bg-slate-700 rounded-lg flex items-center justify-center">
<File className="w-5 h-5 text-slate-600 dark:text-slate-400" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
{file.name}
</p>
<p className="text-xs text-slate-500 dark:text-slate-400">
{formatFileSize(file.size)}
</p>
</div>
</div>
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => removeFile(idx)}
className="h-8 w-8 p-0"
>
<X className="w-4 h-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
))}
<div>
<Progress
value={
plan === 'free'
? Math.min(
(totalSizeMB / PLAN_LIMITS.free.maxFileSizeMB) *
100,
100
)
: Math.min(
((usedMB + totalSizeMB) /
PLAN_LIMITS[plan].maxMonthlyTransferSizeMB) *
100,
100
)
}
className={
isOverLimit ? 'progress-error' : 'progress-success'
}
/>
<p
className={`text-xs mt-1 ${
isOverLimit
? 'text-red-600 font-semibold'
: 'text-gray-600'
}`}
>
Plan: <strong>{plan}</strong> Total:{' '}
{totalSizeMB.toFixed(2)} MB /{' '}
{plan === 'free'
? `${PLAN_LIMITS.free.maxFileSizeMB} MB max per transfer`
: `${remainingMB.toFixed(2)} MB remaining this month`}
</p>
</div>
</div>
</div>
)}
</div>
</div>
{/* Transfer Details Section */}
<div className="space-y-6">
<h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
Transfer Details
</h3>
<div className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="recipientEmail">Recipient Email *</Label>
<Input
id="recipient"
type="email"
placeholder="recipient@example.com"
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="message">Message (Optional)</Label>
<Textarea
id="message"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Add a personal message..."
rows={3}
/>
</div>
<div className="space-y-2">
<Label htmlFor="message">Password *</Label>
<Input
id="password"
type="password"
placeholder="Enter a secure password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<div className="bg-slate-50 dark:bg-slate-800/50 rounded-lg p-4">
<h4 className="font-semibold text-slate-900 dark:text-slate-100 mb-2">
Transfer Summary
</h4>
<div className="space-y-1 text-sm text-slate-600 dark:text-slate-400">
<p>Total Size: {formatFileSize(totalSize)}</p>
<p>Expires: 48 hours after sending</p>
<p>Security: Password protected</p>
</div>
</div>
<div className="bg-slate-50 dark:bg-slate-800/50 rounded-lg p-4">
<UploadStatusToast
step={uploadStep}
progress={uploadProgress}
message={uploadMessage}
/>
</div>
<Button
onClick={handleSubmit}
disabled={isOverLimit}
className="w-full bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700"
size="lg"
>
<>
<Send className="w-4 h-4 mr-2" />
Send Transfer
</>
</Button>
</div>
</div>
</div>
);
}
-31
View File
@@ -1,31 +0,0 @@
'use client';
import * as React from 'react';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from '@/lib/utils';
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = 'horizontal', decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-border',
orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
className
)}
{...props}
/>
)
);
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };
+106
View File
@@ -0,0 +1,106 @@
// Reclaims disk for transfers that are past their expiry or soft-deleted.
//
// Nothing previously removed payloads from UPLOAD_DIR, so every transfer ever
// sent stayed on disk indefinitely regardless of expiresAt.
import { promises as fs } from 'fs'
import path from 'path'
import { prisma } from '@/lib/prisma'
import { UPLOAD_DIR } from '@/lib/config'
import { TransferStatus } from '@prisma/client'
export interface CleanupReport {
markedExpired: number
filesDeleted: number
bytesReclaimed: number
staleTempDirs: number
errors: string[]
}
/** Abandoned chunk directories older than this are removed. */
const TEMP_DIR_MAX_AGE_MS = 24 * 60 * 60 * 1000
/**
* Refuse to unlink anything that does not live under UPLOAD_DIR. Paths come
* from the database, so this is defence against a corrupted or tampered row
* turning cleanup into arbitrary file deletion.
*/
function isInsideUploadDir(target: string): boolean {
const relative = path.relative(UPLOAD_DIR, path.resolve(target))
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)
}
export async function runCleanup(): Promise<CleanupReport> {
const report: CleanupReport = {
markedExpired: 0,
filesDeleted: 0,
bytesReclaimed: 0,
staleTempDirs: 0,
errors: [],
}
const now = new Date()
// 1. Flip lapsed ACTIVE transfers to EXPIRED.
const marked = await prisma.transfer.updateMany({
where: { status: TransferStatus.ACTIVE, expiresAt: { lte: now } },
data: { status: TransferStatus.EXPIRED },
})
report.markedExpired = marked.count
// 2. Delete payloads for transfers that are no longer downloadable. The rows
// are kept so senders retain their history; only the bytes go.
const reclaimable = await prisma.transfer.findMany({
where: { status: { in: [TransferStatus.EXPIRED, TransferStatus.DELETED] } },
include: { files: true },
})
for (const transfer of reclaimable) {
for (const file of transfer.files) {
if (!file.path) continue
if (!isInsideUploadDir(file.path)) {
report.errors.push(`Refusing to delete path outside upload dir: ${file.path}`)
continue
}
try {
const stat = await fs.stat(file.path)
await fs.unlink(file.path)
report.filesDeleted += 1
report.bytesReclaimed += stat.size
} catch (err: unknown) {
const code = (err as NodeJS.ErrnoException)?.code
// Already gone is the expected steady state on repeat runs.
if (code !== 'ENOENT') {
report.errors.push(`${file.path}: ${(err as Error).message}`)
}
}
}
}
// 3. Drop abandoned chunk directories from uploads that never finished.
const tempRoot = path.join(UPLOAD_DIR, '.tmp')
try {
const entries = await fs.readdir(tempRoot, { withFileTypes: true })
for (const entry of entries) {
if (!entry.isDirectory()) continue
const dir = path.join(tempRoot, entry.name)
try {
const stat = await fs.stat(dir)
if (now.getTime() - stat.mtimeMs > TEMP_DIR_MAX_AGE_MS) {
await fs.rm(dir, { recursive: true, force: true })
report.staleTempDirs += 1
}
} catch (err: unknown) {
report.errors.push(`${dir}: ${(err as Error).message}`)
}
}
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
report.errors.push(`temp sweep: ${(err as Error).message}`)
}
}
return report
}
+113
View File
@@ -0,0 +1,113 @@
// Client-side download helper.
//
// The naive approach — `await res.blob()` then createObjectURL — buffers the
// entire decrypted file in memory before anything is written. That is fine for
// small transfers and untenable for multi-gigabyte ones, which is exactly what
// this app exists to move.
//
// Where the File System Access API is available (Chromium), the response body
// is piped straight to a user-chosen file and peak memory stays at roughly one
// chunk. Everywhere else we fall back to the blob path.
interface SaveFilePickerOptions {
suggestedName?: string;
types?: { description: string; accept: Record<string, string[]> }[];
}
interface FileSystemWritable {
write(data: BufferSource | Blob | string): Promise<void>;
close(): Promise<void>;
abort?(reason?: unknown): Promise<void>;
}
interface FileSystemFileHandleLike {
createWritable(): Promise<FileSystemWritable>;
}
type PickerWindow = Window & {
showSaveFilePicker?: (
options?: SaveFilePickerOptions
) => Promise<FileSystemFileHandleLike>;
};
export function supportsStreamingDownload(): boolean {
return (
typeof window !== 'undefined' &&
typeof (window as PickerWindow).showSaveFilePicker === 'function'
);
}
/** Thrown when the user dismisses the save dialog. */
export class DownloadCancelled extends Error {
constructor() {
super('Download cancelled');
this.name = 'DownloadCancelled';
}
}
/**
* Write `response` to disk, streaming when the browser allows it.
* `onProgress` receives bytes written so far.
*/
export async function saveResponseToDisk(
response: Response,
filename: string,
onProgress?: (bytesWritten: number) => void
): Promise<void> {
const picker = (window as PickerWindow).showSaveFilePicker;
if (picker && response.body) {
let handle: FileSystemFileHandleLike;
try {
handle = await picker({ suggestedName: filename });
} catch (err) {
// AbortError means the user closed the dialog; anything else is a real
// failure worth falling back for.
if ((err as DOMException)?.name === 'AbortError') {
throw new DownloadCancelled();
}
return saveViaBlob(response, filename);
}
const writable = await handle.createWritable();
const reader = response.body.getReader();
let written = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
await writable.write(value);
written += value.byteLength;
onProgress?.(written);
}
await writable.close();
} catch (err) {
await writable.abort?.(err).catch(() => {});
throw err;
}
return;
}
return saveViaBlob(response, filename);
}
/**
* Fallback for browsers without the File System Access API. Buffers the whole
* body in memory, so very large transfers may fail here.
*/
async function saveViaBlob(response: Response, filename: string): Promise<void> {
const blob = await response.blob();
const url = URL.createObjectURL(blob);
try {
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
} finally {
// Give the browser a tick to start the download before revoking.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
}
-99
View File
@@ -1,99 +0,0 @@
export async function encryptFile(file: File, password: string) {
const salt = crypto.getRandomValues(new Uint8Array(16))
const iv = crypto.getRandomValues(new Uint8Array(12))
const keyMaterial = await getKeyMaterial(password)
const key = await deriveKey(keyMaterial, salt)
const fileBuffer = await file.arrayBuffer()
const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, fileBuffer)
const encryptedBytes = new Uint8Array(encrypted)
// Combine salt + iv + encrypted data
const combined = new Uint8Array(salt.length + iv.length + encryptedBytes.length)
combined.set(salt, 0)
combined.set(iv, salt.length)
combined.set(encryptedBytes, salt.length + iv.length)
return {
encryptedBlob: new Blob([combined], { type: 'application/octet-stream' }),
metadata: {
salt: Array.from(salt),
iv: Array.from(iv)
}
}
}
async function getKeyMaterial(password: string) {
const enc = new TextEncoder()
return crypto.subtle.importKey(
'raw',
enc.encode(password),
{ name: 'PBKDF2' },
false,
['deriveKey']
)
}
// export async function decryptBlob(blob: Blob, password: string): Promise<Blob> {
// const combined = new Uint8Array(await blob.arrayBuffer())
// const salt = combined.slice(0, 16)
// const iv = combined.slice(16, 28)
// const data = combined.slice(28)
// const keyMaterial = await getKeyMaterial(password)
// const key = await deriveKey(keyMaterial, salt)
// const decrypted = await crypto.subtle.decrypt(
// { name: 'AES-GCM', iv },
// key,
// data
// )
// return new Blob([decrypted])
// }
async function deriveKey(keyMaterial: CryptoKey, salt: Uint8Array) {
return crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt,
iterations: 100000,
hash: 'SHA-256'
},
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
)
}
export async function encryptBlob(blob: Blob, password: string) {
const pwUtf8 = new TextEncoder().encode(password)
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8)
const iv = crypto.getRandomValues(new Uint8Array(12))
const key = await crypto.subtle.importKey('raw', pwHash, 'AES-GCM', false, ['encrypt'])
const content = new Uint8Array(await blob.arrayBuffer())
const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, content)
const encryptedBlob = new Blob([iv, new Uint8Array(encrypted)])
return { encryptedBlob }
}
export async function decryptBlob(encryptedBlob: Blob, password: string) {
const data = new Uint8Array(await encryptedBlob.arrayBuffer())
const iv = data.slice(0, 12)
const encrypted = data.slice(12)
const pwUtf8 = new TextEncoder().encode(password)
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8)
const key = await crypto.subtle.importKey('raw', pwHash, 'AES-GCM', false, ['decrypt'])
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, encrypted)
return new Blob([decrypted])
}
+69
View File
@@ -0,0 +1,69 @@
// Fixed-window rate limiter for password attempts.
//
// SCOPE: this is per-process, in-memory state. It is effective for a single
// server instance, which is what the local-disk storage model already assumes.
// Running several instances behind a load balancer would give each its own
// counter, multiplying the effective limit by the instance count — moving to a
// shared store (Redis) is a prerequisite for scaling out.
type Bucket = { count: number; resetAt: number }
const buckets = new Map<string, Bucket>()
// Bound the map so a flood of distinct keys cannot grow it without limit.
const MAX_KEYS = 10000
function sweep(now: number) {
for (const [key, bucket] of buckets) {
if (bucket.resetAt <= now) buckets.delete(key)
}
}
export interface RateLimitResult {
allowed: boolean
remaining: number
/** Seconds until the window resets. Suitable for a Retry-After header. */
retryAfter: number
}
/**
* Consume one unit against `key`. Returns whether the caller is under the limit.
*/
export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult {
const now = Date.now()
const existing = buckets.get(key)
if (!existing || existing.resetAt <= now) {
if (buckets.size >= MAX_KEYS) sweep(now)
const resetAt = now + windowMs
buckets.set(key, { count: 1, resetAt })
return { allowed: true, remaining: limit - 1, retryAfter: Math.ceil(windowMs / 1000) }
}
existing.count += 1
const retryAfter = Math.max(1, Math.ceil((existing.resetAt - now) / 1000))
return {
allowed: existing.count <= limit,
remaining: Math.max(0, limit - existing.count),
retryAfter,
}
}
/**
* Clear the counter for a key — call after a successful authentication so a
* legitimate user who mistyped a few times is not left throttled.
*/
export function resetRateLimit(key: string) {
buckets.delete(key)
}
/**
* Best-effort client identifier. x-forwarded-for is only trustworthy behind a
* proxy that overwrites it; treat this as a speed bump, not an identity.
*/
export function clientKey(headers: Headers): string {
const forwarded = headers.get('x-forwarded-for')
if (forwarded) return forwarded.split(',')[0]!.trim()
return headers.get('x-real-ip') || 'unknown'
}