The embeddable /badge/<user>.svg route (deployed 2026-11-27) rendered a confident-looking badge for any handle, real or not. It now looks the user up via the existing explicit-select GET /v1/users/:id route and renders a neutral "not found" SVG (HTTP 404) for unknown handles, while showing a live post count for real ones. The lookup fails open (no 404) on a slow/unreachable backend so this stays a reliable public image endpoint rather than a hard API dependency. Also adds the two missing pieces from the Hashnode-style backlink wedge: a "copy badge" icon button on a user's own profile (copies the markdown snippet) and a /docs/badge page explaining the URL, markdown/HTML snippets, and the privacy posture (username + public post count only, same fields already on any public profile). Verified locally end-to-end: started the real backend (local Postgres) + web dev server — an existing seeded user returns 200 with a live post count, an unknown handle returns the 404 SVG, invalid characters still 400, and killing the backend falls back to the neutral badge instead of a false 404. `tsc --noEmit` clean across the whole web app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
188 lines
6.7 KiB
TypeScript
188 lines
6.7 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { RITGRAM_SITE_URL } from '@/lib/site-config'
|
|
|
|
/**
|
|
* GET /badge/<user>.svg
|
|
*
|
|
* Embeddable backlink badge for a Ritgram profile — the Hashnode-style
|
|
* "powered by" wedge: any user can drop
|
|
* [](https://ritgram.rithub.dev/<user>)
|
|
* into their own README/site and it renders a small two-segment SVG badge
|
|
* that links back to their live profile here.
|
|
*
|
|
* Static, cached, no auth, no new npm packages. The username IS checked
|
|
* against the backend (RIT-SEO follow-up, 2026-11-30): a real lookup via
|
|
* the existing public `GET /v1/users/:usernameOrId` route (explicit-select
|
|
* controller, no PII — see userController.ts's 2026-11-17 email-leak fix)
|
|
* so unknown handles render a neutral 404 badge instead of a confident-
|
|
* looking badge for a user that doesn't exist. The lookup is best-effort:
|
|
* a slow/unreachable backend fails OPEN to the neutral "no data" badge
|
|
* (not a 404) rather than making this public image endpoint a hard
|
|
* dependency on the API being up.
|
|
*/
|
|
|
|
const SITE_URL = RITGRAM_SITE_URL
|
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api'
|
|
const LOOKUP_TIMEOUT_MS = 2500
|
|
|
|
const MAX_USER_LEN = 39 // matches the handle length cap used elsewhere in this app
|
|
|
|
function escapeXml(value: string): string {
|
|
return value
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''')
|
|
}
|
|
|
|
/** Rough monospace-ish character width in px at the badge's 11px font size. */
|
|
function textWidth(text: string): number {
|
|
return Math.round(text.length * 6.7) + 20
|
|
}
|
|
|
|
function renderBadgeSvg(
|
|
user: string,
|
|
profileUrl: string,
|
|
options: { value?: string; valueColor?: string } = {}
|
|
): string {
|
|
const label = 'ritgram'
|
|
const value = options.value || `@${user}`
|
|
const valueColor = options.valueColor || '#7c3aed'
|
|
const labelWidth = textWidth(label)
|
|
const valueWidth = textWidth(value)
|
|
const width = labelWidth + valueWidth
|
|
const height = 20
|
|
const safeLabel = escapeXml(label)
|
|
const safeValue = escapeXml(value)
|
|
const safeHref = escapeXml(profileUrl)
|
|
const safeTitle = escapeXml(`${value} on Ritgram`)
|
|
|
|
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${width}" height="${height}" role="img" aria-label="${safeTitle}">
|
|
<title>${safeTitle}</title>
|
|
<a xlink:href="${safeHref}" target="_blank" rel="noopener">
|
|
<linearGradient id="smooth" x2="0" y2="100%">
|
|
<stop offset="0" stop-color="#fff" stop-opacity=".1"/>
|
|
<stop offset="1" stop-opacity=".1"/>
|
|
</linearGradient>
|
|
<clipPath id="round">
|
|
<rect width="${width}" height="${height}" rx="3" fill="#fff"/>
|
|
</clipPath>
|
|
<g clip-path="url(#round)">
|
|
<rect width="${labelWidth}" height="${height}" fill="#1a1a2e"/>
|
|
<rect x="${labelWidth}" width="${valueWidth}" height="${height}" fill="${valueColor}"/>
|
|
<rect width="${width}" height="${height}" fill="url(#smooth)"/>
|
|
</g>
|
|
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
|
<text x="${labelWidth / 2}" y="14">${safeLabel}</text>
|
|
<text x="${labelWidth + valueWidth / 2}" y="14">${safeValue}</text>
|
|
</g>
|
|
</a>
|
|
</svg>`
|
|
}
|
|
|
|
function renderNotFoundSvg(user: string): string {
|
|
const label = 'ritgram'
|
|
const value = 'not found'
|
|
const labelWidth = textWidth(label)
|
|
const valueWidth = textWidth(value)
|
|
const width = labelWidth + valueWidth
|
|
const height = 20
|
|
const safeLabel = escapeXml(label)
|
|
const safeValue = escapeXml(value)
|
|
const safeTitle = escapeXml(`@${user} is not a Ritgram user`)
|
|
|
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" role="img" aria-label="${safeTitle}">
|
|
<title>${safeTitle}</title>
|
|
<clipPath id="round">
|
|
<rect width="${width}" height="${height}" rx="3" fill="#fff"/>
|
|
</clipPath>
|
|
<g clip-path="url(#round)">
|
|
<rect width="${labelWidth}" height="${height}" fill="#1a1a2e"/>
|
|
<rect x="${labelWidth}" width="${valueWidth}" height="${height}" fill="#44475a"/>
|
|
</g>
|
|
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
|
<text x="${labelWidth / 2}" y="14">${safeLabel}</text>
|
|
<text x="${labelWidth + valueWidth / 2}" y="14">${safeValue}</text>
|
|
</g>
|
|
</svg>`
|
|
}
|
|
|
|
interface BadgeLookup {
|
|
/** `undefined` means the lookup didn't resolve either way (timeout/network/5xx) — treat as unknown, not missing. */
|
|
exists: boolean | undefined
|
|
postsCount?: number
|
|
}
|
|
|
|
/**
|
|
* Best-effort existence + post-count check against the public, explicit-
|
|
* select user route. Never throws: any failure resolves to `exists: undefined`
|
|
* so the caller can fail open to the neutral badge instead of a false 404.
|
|
*/
|
|
async function lookupUser(user: string): Promise<BadgeLookup> {
|
|
const controller = new AbortController()
|
|
const timeout = setTimeout(() => controller.abort(), LOOKUP_TIMEOUT_MS)
|
|
|
|
try {
|
|
const res = await fetch(`${API_URL}/v1/users/${encodeURIComponent(user)}`, {
|
|
signal: controller.signal,
|
|
headers: { Accept: 'application/json' },
|
|
cache: 'no-store',
|
|
})
|
|
|
|
if (res.status === 404) {
|
|
return { exists: false }
|
|
}
|
|
|
|
if (!res.ok) {
|
|
return { exists: undefined }
|
|
}
|
|
|
|
const data = await res.json()
|
|
const postsCount = typeof data?.postsCount === 'number' ? data.postsCount : undefined
|
|
return { exists: true, postsCount }
|
|
} catch {
|
|
return { exists: undefined }
|
|
} finally {
|
|
clearTimeout(timeout)
|
|
}
|
|
}
|
|
|
|
export async function GET(_req: NextRequest, { params }: { params: { user: string } }) {
|
|
const raw = decodeURIComponent(params.user || '')
|
|
const user = raw.replace(/\.svg$/i, '').trim()
|
|
|
|
if (!user || user.length > MAX_USER_LEN || !/^[A-Za-z0-9_-]+$/.test(user)) {
|
|
return NextResponse.json({ error: 'invalid or missing username' }, { status: 400 })
|
|
}
|
|
|
|
const profileUrl = `${SITE_URL}/${user}`
|
|
const { exists, postsCount } = await lookupUser(user)
|
|
|
|
if (exists === false) {
|
|
return new NextResponse(renderNotFoundSvg(user), {
|
|
status: 404,
|
|
headers: {
|
|
'Content-Type': 'image/svg+xml; charset=utf-8',
|
|
// Short cache: a handle that doesn't exist yet today may be
|
|
// claimed tomorrow, and this badge should pick that up quickly.
|
|
'Cache-Control': 'public, max-age=300, s-maxage=600',
|
|
},
|
|
})
|
|
}
|
|
|
|
const value =
|
|
typeof postsCount === 'number'
|
|
? `@${user} · ${postsCount} post${postsCount === 1 ? '' : 's'}`
|
|
: undefined
|
|
const svg = renderBadgeSvg(user, profileUrl, { value })
|
|
|
|
return new NextResponse(svg, {
|
|
status: 200,
|
|
headers: {
|
|
'Content-Type': 'image/svg+xml; charset=utf-8',
|
|
'Cache-Control': 'public, max-age=3600, s-maxage=86400',
|
|
},
|
|
})
|
|
}
|