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
130 changes: 130 additions & 0 deletions backend/src/__tests__/modules/profile/og-shell.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { once } from 'node:events';
import type { Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { runInNewContext } from 'node:vm';
import express from 'express';
import { Types } from 'mongoose';
import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest';
import { PublicProfile } from '../../../db/models/publicProfile.model.js';
import { ProfileView } from '../../../db/models/profileView.model.js';
import { User } from '../../../db/models/user.model.js';
import { UserSettings } from '../../../db/models/userSettings.model.js';
import { registerPublicProfileShell } from '../../../modules/profile/ogShell.routes.js';
import { cacheManager } from '../../../shared/cache/cacheManager.js';

const origin = 'https://portfolio.example.test';
let server: Server;
let base: string;

beforeAll(async () => {
const app = express();
registerPublicProfileShell(app, origin);
server = app.listen(0, '127.0.0.1');
await once(server, 'listening');
base = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
});

afterAll(async () => {
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
});

afterEach(() => vi.restoreAllMocks());

async function makeProfile(slug: string, indexable = true) {
return PublicProfile.create({
userId: new Types.ObjectId(),
username: slug,
slug,
visibility: 'public',
isIndexable: indexable,
snapshot: { identity: { displayName: 'Sam & Jules <Team>' } },
seo: {
ogDescription: 'Builds "fast" APIs & <services>',
ogImageUrl: 'https://images.example.test/share.png',
},
});
}

it('returns server-rendered, escaped metadata with a canonical link and noindex', async () => {
const profile = await makeProfile('sam-and-jules', false);
const response = await fetch(base + '/u/sam-and-jules', { headers: { 'User-Agent': 'Slackbot-LinkExpanding' } });
expect(response.status).toBe(200);
expect(response.headers.get('content-type')).toContain('text/html');
const html = await response.text();
expect(html).toContain('<title>Sam &amp; Jules &lt;Team&gt; - DevTrack Portfolio</title>');
expect(html).toContain('<meta property="og:description" content="Builds &quot;fast&quot; APIs &amp; &lt;services&gt;">');
expect(html).toContain('<meta property="og:image" content="https://images.example.test/share.png">');
expect(html).toContain('<meta name="twitter:card" content="summary_large_image">');
expect(html).toContain('<meta name="robots" content="noindex">');
expect(html).toContain('<link rel="canonical" href="' + origin + '/u/sam-and-jules">');
expect(html).toContain('<a id="portfolio-link" href="' + origin + '/portfolio/sam-and-jules">');
expect(html).not.toContain('<Team>');
expect(await ProfileView.countDocuments({ profileUserId: profile.userId })).toBe(0);
});

it('serves a same-origin script that transfers browsers to the public SPA route', async () => {
const response = await fetch(base + '/u/.well-known/portfolio-redirect.js');
expect(response.status).toBe(200);
expect(response.headers.get('content-type')).toContain('javascript');
const href = origin + '/portfolio/sam-and-jules';
const replace = vi.fn();
runInNewContext(await response.text(), {
window: { location: { replace } },
document: { getElementById: () => ({ href }) },
});
expect(replace).toHaveBeenCalledExactlyOnceWith(href);
});

it('redirects uppercase slugs and leaves unpublished user accounts unpublished', async () => {
await User.create({
clerkId: 'clerk_unpublished', username: 'unpublished',
email: 'unpublished@example.test', displayName: 'Unpublished',
});
const upper = await fetch(base + '/u/Sam.And.Jules', { redirect: 'manual' });
expect(upper.status).toBe(301);
expect(upper.headers.get('location')).toBe(origin + '/u/sam.and.jules');
expect((await fetch(base + '/u/unpublished')).status).toBe(404);
expect(await PublicProfile.exists({ slug: 'unpublished' })).toBeNull();
});

it('reuses the template and bypasses cache rendering for matching validators', async () => {
const profile = await makeProfile('cache-test');
await PublicProfile.updateOne({ _id: profile._id }, { $set: { 'seo.ogImageUrl': null } });
const cache = vi.spyOn(cacheManager, 'getOrSet');
const endpoint = base + '/u/cache-test';
const initial = await fetch(endpoint);
const tag = initial.headers.get('etag')!;
const html = await initial.text();
expect(tag).toMatch(/^W\/"[^"]+"$/);
expect(html).toContain(origin + '/portfolio-preview.png');
expect(cache).toHaveBeenCalledExactlyOnceWith(expect.stringMatching(/^cache:portfolio-shell:/), expect.any(Function), 300);

expect(await (await fetch(endpoint)).text()).toBe(html);
const conditional = await fetch(endpoint, { headers: { 'If-None-Match': '"other", ' + tag } });
expect(conditional.status).toBe(304);
expect(await conditional.text()).toBe('');
expect(cache).toHaveBeenCalledTimes(1);

await PublicProfile.updateOne({ _id: profile._id }, { $set: { isIndexable: false } });
const changed = await fetch(endpoint, { headers: { 'If-None-Match': tag } });
expect(changed.status).toBe(200);
expect(changed.headers.get('etag')).not.toBe(tag);
expect(await changed.text()).toContain('content="noindex"');
});

it('rechecks both privacy sources before honoring an old ETag', async () => {
const profile = await makeProfile('privacy-test');
const endpoint = base + '/u/privacy-test';
const initial = await fetch(endpoint);
const tag = initial.headers.get('etag')!;
await initial.text();
expect(initial.status).toBe(200);
await UserSettings.create({ userId: profile.userId, privacy: { profileVisibility: 'private' } });
const settingsPrivate = await fetch(endpoint, { headers: { 'If-None-Match': tag } });
expect(settingsPrivate.status).toBe(404);
expect(settingsPrivate.headers.get('cache-control')).toBe('no-store');
await UserSettings.deleteOne({ userId: profile.userId });

await PublicProfile.updateOne({ _id: profile._id }, { $set: { visibility: 'recruiter_only' } });
expect((await fetch(endpoint, { headers: { 'If-None-Match': tag } })).status).toBe(404);
});
3 changes: 3 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { getInfrastructureState, setApiStatus, type InfrastructureState } from '
import routes from './routes/index.js';
import { getRegisteredWorkerStatuses } from './shared/jobs/workers.js';
import { dlqRoutes } from './routes/dlq.routes.js';
import { registerPublicProfileShell } from './modules/profile/ogShell.routes.js';
import { mountApiRoutes } from './routes/mount.js';
import { sanitizeMongoError } from './db/connection.js';

Expand Down Expand Up @@ -84,6 +85,8 @@ export async function createApp(): Promise<express.Express> {
// Phase 2: Health & observability endpoints (before routes)
setupHealthEndpoints(app, getRedisHealth, getWorkerStatus, getXpWorkerStatus, getOrCreateQueue, QueueNames, eventBus, syncState, getInfrastructureState);

registerPublicProfileShell(app, env.CORS_ORIGIN);

// Phase 3: API routes
app.use('/api/system/dlq', dlqRoutes);
mountApiRoutes(app, routes);
Expand Down
149 changes: 149 additions & 0 deletions backend/src/modules/profile/ogShell.routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { createHash } from 'node:crypto';
import type { Express } from 'express';
import { asyncHandler } from '../../middleware/error.js';
import { cacheManager } from '../../shared/cache/cacheManager.js';
import { PublicProfileService } from './publicProfile.service.js';

const CACHE_TTL_SECONDS = 300;
const CACHE_MAX_ENTRIES = 512;
const TEMPLATE_VERSION = 'v1';
const REDIRECT_SCRIPT_PATH = '/u/.well-known/portfolio-redirect.js';

const ENTITIES: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
};

function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, character => ENTITIES[character]);
}

function httpsImage(value: string | null | undefined): string | undefined {
if (!value) return undefined;
try {
const url = new URL(value);
if (url.protocol === 'https:' && !url.username && !url.password) return url.href;
} catch {
// A malformed image URL falls back to the portfolio preview.
}
}

interface Shell {
title: string;
description: string;
canonical: string;
destination: string;
image: string;
isIndexable: boolean;
}

function renderShell(shell: Shell): string {
const { isIndexable } = shell;
const title = escapeHtml(shell.title);
const description = escapeHtml(shell.description);
const canonical = escapeHtml(shell.canonical);
const destination = escapeHtml(shell.destination);
const image = escapeHtml(shell.image);
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title}</title>
<link rel="canonical" href="${canonical}">
<meta name="description" content="${description}">
<meta property="og:type" content="profile">
<meta property="og:url" content="${canonical}">
<meta property="og:title" content="${title}">
<meta property="og:description" content="${description}">
<meta property="og:image" content="${image}">
<meta name="twitter:card" content="summary_large_image">
${isIndexable ? '' : '<meta name="robots" content="noindex">'}
<script src="${REDIRECT_SCRIPT_PATH}" defer></script>
</head>
<body>
<a id="portfolio-link" href="${destination}">Open portfolio</a>
</body>
</html>`;
}

export function registerPublicProfileShell(app: Express, frontendUrl: string): void {
// Use the configured frontend origin for canonical URLs and browser navigation.
const frontend = URL.canParse(frontendUrl) ? new URL(frontendUrl) : undefined;
const origin = frontend && /^https?:$/.test(frontend.protocol)
? frontend.origin
: 'http://localhost:5173';
const templates = new Map<string, { html: string; expiresAt: number }>();

app.get(REDIRECT_SCRIPT_PATH, (_req, res) => {
res.set('Cache-Control', 'public, max-age=300').type('js')
.send("window.location.replace(document.getElementById('portfolio-link').href);");
});

app.get('/u/:username', asyncHandler(async (req, res) => {
res.set('Cache-Control', 'no-store');
const username = req.params.username;
if (typeof username !== 'string' || username.length < 3 || username.length > 30
|| /^[.]+$/.test(username) || /[/\\\u0000-\u001f\u007f]/.test(username)) {
res.status(404).type('text').send('Public profile not found');
return;
}
const normalized = username.toLowerCase();
const slug = encodeURIComponent(normalized);
const canonical = origin + '/u/' + slug;
if (username !== normalized) {
res.redirect(301, canonical);
return;
}

// The database remains authoritative for every request, including 304s.
const profile = await PublicProfileService.getPublishedPreview(normalized);
if (!profile) {
res.status(404).type('text').send('Public profile not found');
return;
}
const shell: Shell = {
title: profile.displayName + ' - DevTrack Portfolio',
description: profile.description,
canonical,
destination: origin + '/portfolio/' + slug,
image: httpsImage(profile.imageUrl) ?? origin + '/portfolio-preview.png',
isIndexable: profile.isIndexable,
};

const version = createHash('sha256').update(JSON.stringify([TEMPLATE_VERSION, shell])).digest('base64url');
const tag = '"' + version + '"';
res.set({
'Cache-Control': 'public, max-age=0, must-revalidate',
ETag: 'W/' + tag,
});
const validators = req.get('If-None-Match')?.split(',').map(value => value.trim());
if (validators?.some(value => value === '*' || value.replace(/^W\//, '') === tag)) {
res.status(304).end();
return;
}

const cached = templates.get(version);
if (cached && cached.expiresAt > Date.now()) {
res.type('html').send(cached.html);
return;
}

const cachedHtml = await cacheManager.getOrSet<unknown>(
'cache:portfolio-shell:' + version,
async () => renderShell(shell),
CACHE_TTL_SECONDS,
);
const html = typeof cachedHtml === 'string' ? cachedHtml : renderShell(shell);
templates.delete(version);
templates.set(version, { html, expiresAt: Date.now() + CACHE_TTL_SECONDS * 1000 });
if (templates.size > CACHE_MAX_ENTRIES) {
const eldest = templates.keys().next();
if (!eldest.done) templates.delete(eldest.value);
}
res.type('html').send(html);
}));
}
5 changes: 2 additions & 3 deletions backend/src/modules/profile/profile.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export async function getAchievements(req: AuthenticatedRequest, res: Response):
}, 'Achievements retrieved successfully');
}

import { PublicProfileService } from './publicProfile.service.js';
import { canViewPublicProfile, PublicProfileService } from './publicProfile.service.js';
import { UserSettings } from '../../db/models/userSettings.model.js';
import { mapToPublicProfileDTO } from './profile.dto.js';

Expand Down Expand Up @@ -118,8 +118,7 @@ export async function getPublicProfile(req: AuthenticatedRequest, res: Response)
}

const settings = await UserSettings.findOne({ userId: profile.userId }).select('privacy').lean();
if (profile.visibility !== 'public' ||
(settings?.privacy?.profileVisibility && settings.privacy.profileVisibility !== 'public')) {
if (!canViewPublicProfile(profile, settings?.privacy)) {
commonErrors.notFound(res, 'Public Profile');
return;
}
Expand Down
29 changes: 28 additions & 1 deletion backend/src/modules/profile/publicProfile.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PublicProfile } from '../../db/models/publicProfile.model.js';
import { UserSettings, type IUserSettings } from '../../db/models/userSettings.model.js';
import { PublicProfile, type IPublicProfile } from '../../db/models/publicProfile.model.js';
import { User } from '../../db/models/user.model.js';
import { PlatformStats } from '../../db/models/platformStats.model.js';
import { ActivityEvent } from '../../db/models/activityEvent.model.js';
Expand All @@ -22,7 +23,33 @@ function numericStat(value: unknown, fallback = 0): number {
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
}

export function canViewPublicProfile(
profile: Pick<IPublicProfile, 'visibility'>,
privacy?: Partial<IUserSettings['privacy']>,
): boolean {
return profile.visibility === 'public'
&& (!privacy?.profileVisibility || privacy.profileVisibility === 'public');
}

export class PublicProfileService {
/** Read only explicitly public snapshot metadata. Crawlers do not count as profile views. */
static async getPublishedPreview(slug: string) {
const profile = await PublicProfile.findOne({ slug, visibility: 'public' })
.select('userId username visibility isIndexable snapshot.identity.displayName seo.ogDescription seo.ogImageUrl')
.lean();
if (!profile) return null;

const settings = await UserSettings.findOne({ userId: profile.userId }).select('privacy.profileVisibility').lean();
if (!canViewPublicProfile(profile, settings?.privacy)) return null;

return {
displayName: profile.snapshot?.identity?.displayName || profile.username,
description: profile.seo?.ogDescription || 'View this verified engineering portfolio on DevTrack.',
imageUrl: profile.seo?.ogImageUrl,
isIndexable: profile.isIndexable !== false,
};
}

/**
* Recompute the public profile snapshot for a user based on verified signals.
*/
Expand Down
7 changes: 6 additions & 1 deletion frontend/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ server {
add_header Cache-Control "public, immutable";
}

# SPA fallback - all routes return index.html
# Serve crawler metadata before sending browsers to the portfolio SPA route.
location /u/ {
proxy_pass http://api:3001;
}

# SPA fallback - all other routes return index.html
location / {
try_files $uri $uri/ /index.html;
}
Expand Down
Binary file added frontend/public/portfolio-preview.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 3 additions & 3 deletions frontend/src/pages/ProfilePage.public.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ describe('public profile route /u/:username', () => {
);
}

it('renders for a signed-out visitor without redirecting to /login', async () => {
renderAt('/u/someone');
expect(await screen.findByText('Verified Proof-of-Work')).toBeTruthy();
it.each(['/u/someone', '/portfolio/someone'])('renders %s for a signed-out visitor', async path => {
renderAt(path);
expect(await screen.findByText('Verified Proof-of-Work', {}, { timeout: 5000 })).toBeTruthy();
expect(await screen.findByText('Some One')).toBeTruthy();
expect(screen.queryByText('Login')).toBeNull();
});
Expand Down
Loading
Loading