|
| 1 | +import { createHash } from 'crypto' |
| 2 | +import { createLogger } from '@sim/logger' |
| 3 | +import { getErrorMessage } from '@sim/utils/errors' |
| 4 | +import { truncate } from '@sim/utils/string' |
| 5 | +import * as cheerio from 'cheerio' |
| 6 | +import type { NextRequest } from 'next/server' |
| 7 | +import { NextResponse } from 'next/server' |
| 8 | +import type { LinkPreview } from '@/lib/api/contracts/link-preview' |
| 9 | +import { getLinkPreviewContract } from '@/lib/api/contracts/link-preview' |
| 10 | +import { parseRequest } from '@/lib/api/server' |
| 11 | +import { getSession } from '@/lib/auth' |
| 12 | +import { getRedisClient } from '@/lib/core/config/redis' |
| 13 | +import { enforceUserRateLimit } from '@/lib/core/rate-limiter/route-helpers' |
| 14 | +import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server' |
| 15 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 16 | + |
| 17 | +const logger = createLogger('LinkPreviewAPI') |
| 18 | + |
| 19 | +const FETCH_TIMEOUT_MS = 5000 |
| 20 | +const MAX_RESPONSE_BYTES = 256 * 1024 |
| 21 | +const MAX_REDIRECTS = 3 |
| 22 | +const TITLE_MAX_CHARS = 200 |
| 23 | +const DESCRIPTION_MAX_CHARS = 300 |
| 24 | +const CACHE_TTL_SECONDS = 24 * 60 * 60 |
| 25 | +const NEGATIVE_CACHE_TTL_SECONDS = 60 * 60 |
| 26 | +const CACHE_KEY_PREFIX = 'link-preview:v1:' |
| 27 | + |
| 28 | +/** |
| 29 | + * Parses preview metadata from the fetched document (already capped at |
| 30 | + * MAX_RESPONSE_BYTES); cheerio handles attribute order, quoting, and entity |
| 31 | + * decoding. |
| 32 | + */ |
| 33 | +function parsePreview(html: string): LinkPreview { |
| 34 | + const $ = cheerio.load(html) |
| 35 | + |
| 36 | + const meta = (key: string): string | null => { |
| 37 | + const value = $(`meta[property="${key}"], meta[name="${key}"]`).first().attr('content') |
| 38 | + return value?.trim() || null |
| 39 | + } |
| 40 | + |
| 41 | + const title = |
| 42 | + meta('og:title') ?? meta('twitter:title') ?? ($('title').first().text().trim() || null) |
| 43 | + const description = meta('og:description') ?? meta('twitter:description') ?? meta('description') |
| 44 | + const siteName = meta('og:site_name') |
| 45 | + |
| 46 | + if (!title && !description && !siteName) return null |
| 47 | + return { |
| 48 | + title: title ? truncate(title, TITLE_MAX_CHARS) : null, |
| 49 | + description: description ? truncate(description, DESCRIPTION_MAX_CHARS) : null, |
| 50 | + siteName: siteName ? truncate(siteName, TITLE_MAX_CHARS) : null, |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +async function fetchPreview(url: string): Promise<LinkPreview> { |
| 55 | + const response = await secureFetchWithValidation(url, { |
| 56 | + timeout: FETCH_TIMEOUT_MS, |
| 57 | + maxRedirects: MAX_REDIRECTS, |
| 58 | + maxResponseBytes: MAX_RESPONSE_BYTES, |
| 59 | + headers: { |
| 60 | + 'User-Agent': 'Simbot/1.0 (+https://sim.ai)', |
| 61 | + Accept: 'text/html,application/xhtml+xml', |
| 62 | + }, |
| 63 | + }) |
| 64 | + if (response.status < 200 || response.status >= 300) return null |
| 65 | + const contentType = response.headers.get('content-type') ?? '' |
| 66 | + if (!contentType.includes('text/html') && !contentType.includes('application/xhtml+xml')) { |
| 67 | + return null |
| 68 | + } |
| 69 | + return parsePreview(await response.text()) |
| 70 | +} |
| 71 | + |
| 72 | +export const GET = withRouteHandler(async (request: NextRequest) => { |
| 73 | + const session = await getSession() |
| 74 | + if (!session?.user?.id) { |
| 75 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 76 | + } |
| 77 | + |
| 78 | + const rateLimited = await enforceUserRateLimit('link-preview', session.user.id) |
| 79 | + if (rateLimited) return rateLimited |
| 80 | + |
| 81 | + const parsed = await parseRequest(getLinkPreviewContract, request, {}) |
| 82 | + if (!parsed.success) return parsed.response |
| 83 | + const { url } = parsed.data.query |
| 84 | + |
| 85 | + if (!url.startsWith('https://')) { |
| 86 | + return NextResponse.json({ preview: null }) |
| 87 | + } |
| 88 | + |
| 89 | + const redis = getRedisClient() |
| 90 | + const cacheKey = `${CACHE_KEY_PREFIX}${createHash('sha256').update(url).digest('hex')}` |
| 91 | + if (redis) { |
| 92 | + try { |
| 93 | + const cached = await redis.get(cacheKey) |
| 94 | + if (cached !== null) { |
| 95 | + return NextResponse.json({ preview: JSON.parse(cached) }) |
| 96 | + } |
| 97 | + } catch (error) { |
| 98 | + logger.warn('Link preview cache read failed', { error }) |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + let preview: LinkPreview = null |
| 103 | + try { |
| 104 | + preview = await fetchPreview(url) |
| 105 | + } catch (error) { |
| 106 | + logger.info('Link preview fetch failed; returning null preview', { |
| 107 | + host: new URL(url).hostname, |
| 108 | + error: getErrorMessage(error, 'unknown error').replaceAll(url, '[url]'), |
| 109 | + }) |
| 110 | + } |
| 111 | + |
| 112 | + if (redis) { |
| 113 | + const ttl = preview ? CACHE_TTL_SECONDS : NEGATIVE_CACHE_TTL_SECONDS |
| 114 | + try { |
| 115 | + await redis.set(cacheKey, JSON.stringify(preview), 'EX', ttl) |
| 116 | + } catch (error) { |
| 117 | + logger.warn('Link preview cache write failed', { error }) |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + return NextResponse.json({ preview }) |
| 122 | +}) |
0 commit comments