diff --git a/src/app/api/profile/photo/__tests__/route.test.ts b/src/app/api/profile/photo/__tests__/route.test.ts new file mode 100644 index 0000000..67cfdee --- /dev/null +++ b/src/app/api/profile/photo/__tests__/route.test.ts @@ -0,0 +1,62 @@ +/** @jest-environment node */ +import { NextRequest } from 'next/server'; +import { POST } from '../route'; +import { requireAdminSession } from '@/lib/admin-auth'; +import { prisma } from '@/lib/prisma'; +import { put, del } from '@vercel/blob'; +import { revalidatePublic } from '@/lib/api'; + +jest.mock('@/lib/admin-auth', () => ({ requireAdminSession: jest.fn() })); +jest.mock('@/lib/prisma', () => ({ prisma: { personalData: { findFirst: jest.fn(), update: jest.fn() } } })); +jest.mock('@vercel/blob', () => ({ put: jest.fn(), del: jest.fn() })); +jest.mock('@/lib/api', () => ({ + revalidatePublic: jest.fn(), + jsonError: (error: string, status: number) => Response.json({ error }, { status }), + handleError: () => Response.json({ error: 'Failed' }, { status: 500 }), +})); +const originalToken = process.env.BLOB_READ_WRITE_TOKEN; +afterAll(() => { + if (originalToken === undefined) delete process.env.BLOB_READ_WRITE_TOKEN; + else process.env.BLOB_READ_WRITE_TOKEN = originalToken; +}); +beforeEach(() => { + jest.resetAllMocks(); + process.env.BLOB_READ_WRITE_TOKEN = 'test-only'; + jest.mocked(requireAdminSession).mockResolvedValue(null); + jest.mocked(prisma.personalData.findFirst).mockResolvedValue({ id: 'profile' } as never); + jest.mocked(put).mockResolvedValue({ url: 'https://example.public.blob.vercel-storage.com/profile/new.png' } as never); + jest.mocked(del).mockResolvedValue(undefined); +}); +function request(bytes: Uint8Array = new Uint8Array([137,80,78,71,13,10,26,10,0,0,0,0])) { + const form = new FormData(); + form.append('file', new Blob([new Uint8Array(bytes)], { type: 'image/png' }), 'photo.png'); + return new NextRequest('http://localhost/api/profile/photo', { method: 'POST', body: form }); +} +test('unauthenticated uploads never reach storage', async () => { + jest.mocked(requireAdminSession).mockResolvedValue(Response.json({}, { status: 401 }) as never); + expect((await POST(request())).status).toBe(401); + expect(put).not.toHaveBeenCalled(); +}); +test('rejects unsupported and oversized files before storage writes', async () => { + expect((await POST(request(new TextEncoder().encode('not a PNG')))).status).toBe(400); + expect((await POST(request(new Uint8Array(4 * 1024 * 1024 + 1)))).status).toBe(413); + expect(put).not.toHaveBeenCalled(); +}); +test('saves uploaded URL and revalidates public pages', async () => { + const response = await POST(request()); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ avatarUrl: 'https://example.public.blob.vercel-storage.com/profile/new.png' }); + expect(prisma.personalData.update).toHaveBeenCalledWith({ where: { id: 'profile' }, data: { avatarUrl: 'https://example.public.blob.vercel-storage.com/profile/new.png' } }); + expect(revalidatePublic).toHaveBeenCalledTimes(1); +}); +test('cleans up only a new blob if saving the profile fails', async () => { + jest.mocked(prisma.personalData.update).mockRejectedValue(new Error('database failure')); + expect((await POST(request())).status).toBe(500); + expect(del).toHaveBeenCalledWith('https://example.public.blob.vercel-storage.com/profile/new.png'); + expect(revalidatePublic).not.toHaveBeenCalled(); +}); +test('missing storage configuration gives an actionable error', async () => { + delete process.env.BLOB_READ_WRITE_TOKEN; + expect((await POST(request())).status).toBe(501); + expect(put).not.toHaveBeenCalled(); +}); diff --git a/src/app/api/profile/photo/route.ts b/src/app/api/profile/photo/route.ts new file mode 100644 index 0000000..31694bd --- /dev/null +++ b/src/app/api/profile/photo/route.ts @@ -0,0 +1,43 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { put, del } from '@vercel/blob'; +import { prisma } from '@/lib/prisma'; +import { requireAdminSession } from '@/lib/admin-auth'; +import { handleError, jsonError, revalidatePublic } from '@/lib/api'; +import { MAX_PHOTO_BYTES, photoFormat } from '@/lib/profile-photo'; + +export const dynamic = 'force-dynamic'; + +export async function POST(request: NextRequest) { + const denied = await requireAdminSession(request); + if (denied) return denied; + if (!process.env.BLOB_READ_WRITE_TOKEN) { + return jsonError('Photo storage is not configured. Connect Vercel Blob or paste a public image URL in Profile.', 501); + } + try { + const personal = await prisma.personalData.findFirst({ select: { id: true } }); + if (!personal) return jsonError('Save your profile first, then upload a photo.', 400); + const form = await request.formData(); + const file = form.get('file'); + if (!(file instanceof File) || !file.size) return jsonError('Choose a photo to upload.', 400); + if (file.size > MAX_PHOTO_BYTES) return jsonError('Photo too large (max 4 MB).', 413); + const bytes = new Uint8Array(await file.arrayBuffer()); + const format = photoFormat(bytes); + if (!format) return jsonError('Only JPG, PNG and WebP photos are allowed.', 400); + const blob = await put(`profile/photo-${Date.now()}.${format.extension}`, new Blob([bytes], { type: format.contentType }), { + access: 'public', + contentType: format.contentType, + addRandomSuffix: true, + }); + try { + await prisma.personalData.update({ where: { id: personal.id }, data: { avatarUrl: blob.url } }); + } catch (error) { + // Remove only this failed upload; never delete previously saved photos. + await del(blob.url).catch(() => undefined); + throw error; + } + revalidatePublic(); + return NextResponse.json({ avatarUrl: blob.url }); + } catch (error) { + return handleError(error, 'Profile photo'); + } +} diff --git a/src/components/admin/profile-panel.tsx b/src/components/admin/profile-panel.tsx index aaca1b3..9a20f30 100644 --- a/src/components/admin/profile-panel.tsx +++ b/src/components/admin/profile-panel.tsx @@ -42,6 +42,8 @@ export function ProfilePanel() { const [reload, setReload] = useState(0); const [saving, setSaving] = useState(false); const [uploading, setUploading] = useState(false); + const [photoUploading, setPhotoUploading] = useState(false); + const photoRef = useRef(null); const fileRef = useRef(null); useEffect(() => { @@ -72,7 +74,7 @@ export function ProfilePanel() { const save = async (e?: FormEvent) => { e?.preventDefault(); - if (loading || loadError || saving) return; + if (loading || loadError || saving || photoUploading) return; setSaving(true); try { await api('/api/personal-data', { method: 'PUT', body: profile }); @@ -101,6 +103,28 @@ export function ProfilePanel() { } }; + const uploadPhoto = async (file: File) => { + if (photoUploading || saving) return; + if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type) || file.size > 4 * 1024 * 1024 || !file.size) { + toast({ title: 'Choose a JPG, PNG or WebP photo under 4 MB', variant: 'destructive' }); + if (photoRef.current) photoRef.current.value = ''; + return; + } + setPhotoUploading(true); + try { + const fd = new FormData(); + fd.append('file', file); + const { avatarUrl } = await api<{ avatarUrl: string }>('/api/profile/photo', { method: 'POST', formData: fd }); + setProfile((p) => ({ ...p, avatarUrl })); + toast({ title: 'Photo uploaded', description: 'Saved. The public site refreshes within a minute.' }); + } catch (err) { + toast({ title: 'Photo upload failed', description: errorMessage(err), variant: 'destructive' }); + } finally { + setPhotoUploading(false); + if (photoRef.current) photoRef.current.value = ''; + } + }; + if (loadError) return ( setReload((value) => value + 1)}>Retry loading @@ -115,7 +139,7 @@ export function ProfilePanel() { title="Profile" description={exists ? 'Shown in the hero, about section and footer.' : 'No profile yet — fill this in and save to create it.'} actions={ - save()} busy={saving}> + save()} busy={saving} disabled={photoUploading}> {exists ? 'Save changes' : 'Create profile'} } @@ -142,8 +166,8 @@ export function ProfilePanel() { - - + + @@ -166,6 +190,20 @@ export function ProfilePanel() { + +
+ {profile.avatarUrl && ( + // eslint-disable-next-line @next/next/no-img-element + Current profile photo + )} + e.target.files?.[0] && uploadPhoto(e.target.files[0])} /> + photoRef.current?.click()} busy={photoUploading} disabled={!exists || saving}> + Upload photo + + {!exists && Create the profile first.} +
+
+
-
+
{/* eslint-disable-next-line @next/next/no-img-element */} {name} {/* red duotone */} -
+
-
-
+
+
{/* HUD */}
diff --git a/src/lib/__tests__/github-sync.test.ts b/src/lib/__tests__/github-sync.test.ts index 68e6111..8c28627 100644 --- a/src/lib/__tests__/github-sync.test.ts +++ b/src/lib/__tests__/github-sync.test.ts @@ -38,3 +38,20 @@ test('preserves settings of a recreated repo and does not clean up after failed test('invalid explicit usernames do not silently sync a different account', async () => { await expect(resolveGitHubUsername(db, 'https://evilgithub.com/owner')).rejects.toMatchObject({ status: 400 }); }); + +test.each([ + ['https://storage.public.blob.vercel-storage.com/profile/photo.jpg', false], + ['https://example.com/my-photo.png', false], + ['https://avatars.githubusercontent.com/u/123?v=4', true], + ['', true], +])('profile sync preserves custom photo %s', async (avatarUrl, shouldUpdate) => { + const personalData = { + findFirst: jest.fn().mockResolvedValue({ id: 'profile', avatarUrl, location: 'Kolkata', github: 'https://github.com/Owner', bio: 'Bio' }), + update: jest.fn(), + }; + api.getUser.mockResolvedValue({ login: 'Owner', avatar_url: 'https://avatars.githubusercontent.com/u/456?v=4' }); + repos.findMany.mockResolvedValue([]); + await syncGitHub({ ...db, personalData } as unknown as PrismaClient, { username: 'Owner' }); + if (shouldUpdate) expect(personalData.update).toHaveBeenCalledWith(expect.objectContaining({ data: { avatarUrl: 'https://avatars.githubusercontent.com/u/456?v=4' } })); + else expect(personalData.update).not.toHaveBeenCalled(); +}); diff --git a/src/lib/__tests__/profile-photo.test.ts b/src/lib/__tests__/profile-photo.test.ts new file mode 100644 index 0000000..94040da --- /dev/null +++ b/src/lib/__tests__/profile-photo.test.ts @@ -0,0 +1,14 @@ +/** @jest-environment node */ +import { photoFormat } from '../profile-photo'; + +test('identifies supported photo bytes independently of MIME and extension', () => { + expect(photoFormat(new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 0]))?.extension).toBe('png'); + expect(photoFormat(new Uint8Array([255, 216, 255, 224, 0, 0, 0, 0, 0, 0, 0, 0]))?.extension).toBe('jpg'); + expect(photoFormat(new TextEncoder().encode('RIFF0000WEBP0000'))?.extension).toBe('webp'); +}); + +test('rejects SVG, HTML, PDFs and truncated uploads', () => { + for (const value of ['', 'not a photo', '%PDF-1.4 fake image', 'RIFF', '']) { + expect(photoFormat(new TextEncoder().encode(value))).toBeNull(); + } +}); diff --git a/src/lib/github-sync.ts b/src/lib/github-sync.ts index c8be839..6b96904 100644 --- a/src/lib/github-sync.ts +++ b/src/lib/github-sync.ts @@ -86,7 +86,13 @@ export async function syncGitHub( const personal = await prisma.personalData.findFirst(); if (personal) { const data: Record = {}; - if (user.avatar_url && personal.avatarUrl !== user.avatar_url) data.avatarUrl = user.avatar_url; + // Refresh GitHub avatars, but preserve uploaded/custom portraits. + let isGitHubAvatar = false; + try { + const host = new URL(personal.avatarUrl || '').hostname; + isGitHubAvatar = host === 'avatars.githubusercontent.com' || host === 'github.com'; + } catch { /* Empty or custom values are handled below. */ } + if (user.avatar_url && (!personal.avatarUrl || isGitHubAvatar) && personal.avatarUrl !== user.avatar_url) data.avatarUrl = user.avatar_url; if (!personal.location && user.location) data.location = titleCase(user.location); if (!personal.github) data.github = user.html_url; if (!personal.bio && user.bio) data.bio = user.bio.trim(); diff --git a/src/lib/profile-photo.ts b/src/lib/profile-photo.ts new file mode 100644 index 0000000..441626c --- /dev/null +++ b/src/lib/profile-photo.ts @@ -0,0 +1,16 @@ +export const MAX_PHOTO_BYTES = 4 * 1024 * 1024; + +/** Inspect bytes rather than trusting the uploaded filename or MIME type. */ +export function photoFormat(bytes: Uint8Array): { extension: string; contentType: string } | null { + if (bytes.length < 12) return null; + if ([137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value)) { + return { extension: 'png', contentType: 'image/png' }; + } + if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) { + return { extension: 'jpg', contentType: 'image/jpeg' }; + } + if (String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF' && String.fromCharCode(...bytes.slice(8, 12)) === 'WEBP') { + return { extension: 'webp', contentType: 'image/webp' }; + } + return null; +}