Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions src/app/api/profile/photo/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -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('<svg>not a PNG</svg>')))).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();
});
43 changes: 43 additions & 0 deletions src/app/api/profile/photo/route.ts
Original file line number Diff line number Diff line change
@@ -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');
}
}
46 changes: 42 additions & 4 deletions src/components/admin/profile-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLInputElement>(null);
const fileRef = useRef<HTMLInputElement>(null);

useEffect(() => {
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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 (
<Panel title="Profile" description="Could not load your profile. Retry before editing.">
<Btn variant="outline" onClick={() => setReload((value) => value + 1)}>Retry loading</Btn>
Expand All @@ -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={
<Btn onClick={() => save()} busy={saving}>
<Btn onClick={() => save()} busy={saving} disabled={photoUploading}>
{exists ? 'Save changes' : 'Create profile'}
</Btn>
}
Expand All @@ -142,8 +166,8 @@ export function ProfilePanel() {
<Field label="LinkedIn URL" htmlFor="p-linkedin">
<TextInput id="p-linkedin" value={profile.linkedin} onChange={set('linkedin')} placeholder="https://www.linkedin.com/in/…" />
</Field>
<Field label="Avatar image URL" htmlFor="p-avatar" hint="Filled automatically by the GitHub sync.">
<TextInput id="p-avatar" value={profile.avatarUrl} onChange={set('avatarUrl')} />
<Field label="Avatar image URL" htmlFor="p-avatar" hint="Upload a photo below or paste a public image URL. Custom photos are preserved during GitHub sync.">
<TextInput id="p-avatar" disabled={photoUploading} value={profile.avatarUrl} onChange={set('avatarUrl')} />
</Field>
<Field label="Resume URL" htmlFor="p-resume" hint="Upload a PDF below or paste any public link (e.g. Google Drive).">
<TextInput id="p-resume" value={profile.resumeUrl} onChange={set('resumeUrl')} />
Expand All @@ -166,6 +190,20 @@ export function ProfilePanel() {
</form>
</Panel>

<Panel title="Profile photo" description="JPG, PNG or WebP, up to 4 MB. Uploading saves the photo immediately.">
<div className="flex flex-wrap items-center gap-4">
{profile.avatarUrl && (
// eslint-disable-next-line @next/next/no-img-element
<img src={profile.avatarUrl} alt="Current profile photo" className="h-20 w-20 border border-signal/40 object-cover" />
)}
<input ref={photoRef} aria-label="Choose profile photo" type="file" accept="image/jpeg,image/png,image/webp" className="hidden" onChange={(e) => e.target.files?.[0] && uploadPhoto(e.target.files[0])} />
<Btn variant="outline" onClick={() => photoRef.current?.click()} busy={photoUploading} disabled={!exists || saving}>
<Upload className="h-3.5 w-3.5" /> Upload photo
</Btn>
{!exists && <span className="text-xs text-muted-foreground">Create the profile first.</span>}
</div>
</Panel>

<Panel title="Resume PDF" description="Stored in Vercel Blob (needs BLOB_READ_WRITE_TOKEN). Max 4 MB.">
<div className="flex flex-wrap items-center gap-4">
<input
Expand Down
10 changes: 5 additions & 5 deletions src/components/sections/about.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,19 @@ export function AboutSection({
{/* portrait */}
<Reveal className="lg:col-span-5">
<TiltCard className="mx-auto max-w-md" max={10}>
<div className="relative aspect-[4/5] overflow-hidden border border-signal/60 bg-ink">
<div tabIndex={0} aria-label={`${name} portrait — hover or focus to view original colors`} className="group/portrait relative aspect-[4/5] overflow-hidden border border-signal/60 bg-ink outline-none focus-visible:ring-2 focus-visible:ring-cyan">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={avatar}
alt={name}
className="absolute inset-0 h-full w-full object-cover grayscale contrast-125"
className="absolute inset-0 h-full w-full object-cover grayscale contrast-125 transition-[filter] duration-700 ease-out group-hover/portrait:grayscale-0 group-hover/portrait:contrast-100 group-focus/portrait:grayscale-0 group-focus/portrait:contrast-100 motion-reduce:transition-none"
loading="lazy"
/>
{/* red duotone */}
<div className="absolute inset-0 bg-signal mix-blend-multiply" />
<div className="pointer-events-none absolute inset-0 bg-signal mix-blend-multiply transition-opacity duration-700 ease-out group-hover/portrait:opacity-0 group-focus/portrait:opacity-0 motion-reduce:transition-none" />
<div className="absolute inset-0 bg-gradient-to-t from-ink via-ink/20 to-transparent" />
<div className="scanline absolute inset-0 opacity-60" />
<div className="animate-scan absolute inset-x-0 top-0 h-24 bg-gradient-to-b from-transparent via-cyan/20 to-transparent" />
<div className="pointer-events-none scanline absolute inset-0 opacity-60 transition-opacity duration-700 group-hover/portrait:opacity-0 group-focus/portrait:opacity-0 motion-reduce:transition-none" />
<div className="pointer-events-none absolute inset-0 transition-opacity duration-700 group-hover/portrait:opacity-0 group-focus/portrait:opacity-0 motion-reduce:transition-none"><div className="animate-scan absolute inset-x-0 top-0 h-24 bg-gradient-to-b from-transparent via-cyan/20 to-transparent" /></div>

{/* HUD */}
<div className="absolute left-3 top-3 monofont text-[10px] uppercase tracking-[0.25em] text-bone">
Expand Down
17 changes: 17 additions & 0 deletions src/lib/__tests__/github-sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
14 changes: 14 additions & 0 deletions src/lib/__tests__/profile-photo.test.ts
Original file line number Diff line number Diff line change
@@ -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 ['<svg onload="alert(1)">', '<html>not a photo</html>', '%PDF-1.4 fake image', 'RIFF', '']) {
expect(photoFormat(new TextEncoder().encode(value))).toBeNull();
}
});
8 changes: 7 additions & 1 deletion src/lib/github-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,13 @@ export async function syncGitHub(
const personal = await prisma.personalData.findFirst();
if (personal) {
const data: Record<string, string> = {};
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();
Expand Down
16 changes: 16 additions & 0 deletions src/lib/profile-photo.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Loading