|
| 1 | +// Server-side link unfurler. |
| 2 | +// |
| 3 | +// Mirrors the desktop DefaultParser |
| 4 | +// (AppFlowy-Premium/frontend/appflowy_flutter/lib/plugins/document/presentation/ |
| 5 | +// editor_plugins/link_preview/link_parsers/default_parser.dart) |
| 6 | +// so web link mentions reach parity with the desktop app: a browser cannot |
| 7 | +// scrape cross-origin pages (CORS), so the same fetch + metadata extraction |
| 8 | +// runs here instead. Prefer Open Graph, fall back to <title>, then host. |
| 9 | +// |
| 10 | +// Dependency-free on purpose: only the <head> meta/link tags are needed, so we |
| 11 | +// parse them directly rather than pulling an HTML parser into the function. |
| 12 | + |
| 13 | +import { isAllowedHttpUrl } from './url-safety'; |
| 14 | + |
| 15 | +const MAX_HTML_BYTES = 50 * 1024; // the <head> carries all the metadata we read |
| 16 | +const REQUEST_TIMEOUT_MS = 8000; |
| 17 | +const DESCRIPTION_MAX_LENGTH = 240; |
| 18 | +const USER_AGENT = 'Mozilla/5.0 (compatible; AppFlowyBot/1.0; +https://appflowy.io)'; |
| 19 | +const MAX_REDIRECTS = 5; |
| 20 | + |
| 21 | +export interface UnfurlImage { |
| 22 | + url: string; |
| 23 | +} |
| 24 | + |
| 25 | +export interface UnfurlResult { |
| 26 | + title: string; |
| 27 | + description: string; |
| 28 | + image?: UnfurlImage; |
| 29 | + logo?: UnfurlImage; |
| 30 | +} |
| 31 | + |
| 32 | +interface FetchedHtml { |
| 33 | + response: Response; |
| 34 | + url: URL; |
| 35 | +} |
| 36 | + |
| 37 | +export async function unfurl(rawUrl: string): Promise<UnfurlResult> { |
| 38 | + const initialUrl = new URL(rawUrl); |
| 39 | + const { response, url } = await fetchHtml(initialUrl); |
| 40 | + const host = url.hostname.replace(/^www\./, ''); |
| 41 | + |
| 42 | + if (!response.ok) { |
| 43 | + void response.body?.cancel().catch(() => undefined); |
| 44 | + throw new Error(`Failed to fetch link preview: ${response.status}`); |
| 45 | + } |
| 46 | + |
| 47 | + const contentType = response.headers.get('content-type')?.toLowerCase() ?? ''; |
| 48 | + |
| 49 | + if (!isHtml(contentType)) { |
| 50 | + void response.body?.cancel().catch(() => undefined); |
| 51 | + return nonHtmlResult(url, host, contentType); |
| 52 | + } |
| 53 | + |
| 54 | + const head = await readHead(response); |
| 55 | + |
| 56 | + return extractMetadata(head, url, host); |
| 57 | +} |
| 58 | + |
| 59 | +async function fetchHtml(url: URL): Promise<FetchedHtml> { |
| 60 | + const controller = new AbortController(); |
| 61 | + const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); |
| 62 | + |
| 63 | + try { |
| 64 | + return await fetchHtmlFollowingAllowedRedirects(url, controller.signal); |
| 65 | + } finally { |
| 66 | + clearTimeout(timer); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +async function fetchHtmlFollowingAllowedRedirects(initialUrl: URL, signal: AbortSignal): Promise<FetchedHtml> { |
| 71 | + let currentUrl = initialUrl; |
| 72 | + |
| 73 | + for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects += 1) { |
| 74 | + if (!isAllowedHttpUrl(currentUrl)) { |
| 75 | + throw new Error('Blocked redirect target'); |
| 76 | + } |
| 77 | + |
| 78 | + const response = await fetch(currentUrl.toString(), { |
| 79 | + redirect: 'manual', |
| 80 | + signal, |
| 81 | + headers: { |
| 82 | + 'User-Agent': USER_AGENT, |
| 83 | + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', |
| 84 | + }, |
| 85 | + }); |
| 86 | + |
| 87 | + if (!isRedirectResponse(response.status)) return { response, url: currentUrl }; |
| 88 | + |
| 89 | + const location = response.headers.get('location'); |
| 90 | + |
| 91 | + void response.body?.cancel().catch(() => undefined); |
| 92 | + if (!location) throw new Error('Redirect response missing Location header'); |
| 93 | + |
| 94 | + const nextUrl = new URL(location, currentUrl); |
| 95 | + |
| 96 | + if (!isAllowedHttpUrl(nextUrl)) { |
| 97 | + throw new Error('Blocked redirect target'); |
| 98 | + } |
| 99 | + |
| 100 | + currentUrl = nextUrl; |
| 101 | + } |
| 102 | + |
| 103 | + throw new Error('Too many redirects'); |
| 104 | +} |
| 105 | + |
| 106 | +function isRedirectResponse(status: number): boolean { |
| 107 | + return status === 301 || status === 302 || status === 303 || status === 307 || status === 308; |
| 108 | +} |
| 109 | + |
| 110 | +function isHtml(contentType: string): boolean { |
| 111 | + return contentType === '' || contentType.includes('text/html') || contentType.includes('application/xhtml'); |
| 112 | +} |
| 113 | + |
| 114 | +// Read only up to </head> (or 50KB) to keep the function fast and cheap. |
| 115 | +async function readHead(response: Response): Promise<string> { |
| 116 | + const reader = response.body?.getReader(); |
| 117 | + |
| 118 | + if (!reader) return response.text(); |
| 119 | + |
| 120 | + const decoder = new TextDecoder('utf-8'); |
| 121 | + let html = ''; |
| 122 | + let received = 0; |
| 123 | + |
| 124 | + while (received < MAX_HTML_BYTES) { |
| 125 | + const { done, value } = await reader.read(); |
| 126 | + |
| 127 | + if (done) break; |
| 128 | + received += value.byteLength; |
| 129 | + html += decoder.decode(value, { stream: true }); |
| 130 | + |
| 131 | + const headEnd = html.toLowerCase().indexOf('</head>'); |
| 132 | + |
| 133 | + if (headEnd !== -1) { |
| 134 | + html = html.slice(0, headEnd + '</head>'.length); |
| 135 | + break; |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + void reader.cancel().catch(() => undefined); |
| 140 | + return html; |
| 141 | +} |
| 142 | + |
| 143 | +function extractMetadata(head: string, url: URL, host: string): UnfurlResult { |
| 144 | + const metas = matchTags(head, 'meta'); |
| 145 | + const links = matchTags(head, 'link'); |
| 146 | + |
| 147 | + const og = (property: string) => metas.find((attrs) => attrs.property === property)?.content; |
| 148 | + const named = (name: string) => metas.find((attrs) => attrs.name === name)?.content; |
| 149 | + |
| 150 | + const title = clean(og('og:title')) || clean(extractTitleTag(head)) || clean(named('title')) || host; |
| 151 | + const description = clean(og('og:description')) || clean(named('description')); |
| 152 | + const image = resolveOptional(url, og('og:image')); |
| 153 | + const favicon = extractFavicon(links, url) ?? defaultFavicon(host); |
| 154 | + |
| 155 | + return { |
| 156 | + title, |
| 157 | + description: truncate(description), |
| 158 | + ...(image ? { image: { url: image } } : {}), |
| 159 | + logo: { url: favicon }, |
| 160 | + }; |
| 161 | +} |
| 162 | + |
| 163 | +function extractFavicon(links: Array<Record<string, string>>, url: URL): string | undefined { |
| 164 | + const rels = ['icon', 'shortcut icon', 'apple-touch-icon', 'apple-touch-icon-precomposed']; |
| 165 | + |
| 166 | + for (const rel of rels) { |
| 167 | + const href = links.find((attrs) => (attrs.rel ?? '').toLowerCase() === rel)?.href; |
| 168 | + |
| 169 | + if (href) return resolveOptional(url, href); |
| 170 | + } |
| 171 | + |
| 172 | + const anyIcon = links.find((attrs) => (attrs.rel ?? '').toLowerCase().includes('icon'))?.href; |
| 173 | + |
| 174 | + return anyIcon ? resolveOptional(url, anyIcon) : undefined; |
| 175 | +} |
| 176 | + |
| 177 | +function matchTags(html: string, tag: 'meta' | 'link'): Array<Record<string, string>> { |
| 178 | + const regex = new RegExp(`<${tag}\\b[^>]*>`, 'gi'); |
| 179 | + |
| 180 | + return (html.match(regex) ?? []).map(parseAttributes); |
| 181 | +} |
| 182 | + |
| 183 | +const ATTR_REGEX = /([a-zA-Z_:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g; |
| 184 | + |
| 185 | +function parseAttributes(tag: string): Record<string, string> { |
| 186 | + const attrs: Record<string, string> = {}; |
| 187 | + let match: RegExpExecArray | null; |
| 188 | + |
| 189 | + ATTR_REGEX.lastIndex = 0; |
| 190 | + while ((match = ATTR_REGEX.exec(tag)) !== null) { |
| 191 | + attrs[match[1].toLowerCase()] = match[2] ?? match[3] ?? match[4] ?? ''; |
| 192 | + } |
| 193 | + |
| 194 | + return attrs; |
| 195 | +} |
| 196 | + |
| 197 | +function extractTitleTag(html: string): string | undefined { |
| 198 | + return /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1]; |
| 199 | +} |
| 200 | + |
| 201 | +function nonHtmlResult(url: URL, host: string, contentType: string): UnfurlResult { |
| 202 | + const filename = url.pathname.split('/').filter(Boolean).pop() || host; |
| 203 | + |
| 204 | + return { |
| 205 | + title: decodeURIComponentSafe(filename), |
| 206 | + description: contentType ? `Type: ${contentType}` : '', |
| 207 | + logo: { url: defaultFavicon(host) }, |
| 208 | + }; |
| 209 | +} |
| 210 | + |
| 211 | +function defaultFavicon(host: string): string { |
| 212 | + return `https://www.google.com/s2/favicons?domain=${host}&sz=128`; |
| 213 | +} |
| 214 | + |
| 215 | +function resolveOptional(base: URL, href?: string): string | undefined { |
| 216 | + if (!href) return undefined; |
| 217 | + |
| 218 | + const decoded = decodeEntities(href).trim(); |
| 219 | + |
| 220 | + if (!decoded) return undefined; |
| 221 | + |
| 222 | + try { |
| 223 | + return new URL(decoded, base).toString(); |
| 224 | + } catch { |
| 225 | + return decoded; |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +function clean(value?: string): string { |
| 230 | + return decodeEntities(value ?? '') |
| 231 | + .replace(/\s+/g, ' ') |
| 232 | + .trim(); |
| 233 | +} |
| 234 | + |
| 235 | +function truncate(value: string): string { |
| 236 | + if (value.length <= DESCRIPTION_MAX_LENGTH) return value; |
| 237 | + return `${value.slice(0, DESCRIPTION_MAX_LENGTH - 1).trimEnd()}…`; |
| 238 | +} |
| 239 | + |
| 240 | +function decodeURIComponentSafe(value: string): string { |
| 241 | + try { |
| 242 | + return decodeURIComponent(value); |
| 243 | + } catch { |
| 244 | + return value; |
| 245 | + } |
| 246 | +} |
| 247 | + |
| 248 | +const NAMED_ENTITIES: Record<string, string> = { |
| 249 | + amp: '&', |
| 250 | + lt: '<', |
| 251 | + gt: '>', |
| 252 | + quot: '"', |
| 253 | + apos: "'", |
| 254 | + nbsp: ' ', |
| 255 | +}; |
| 256 | + |
| 257 | +function decodeEntities(value: string): string { |
| 258 | + return value.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (match, entity: string) => { |
| 259 | + if (entity[0] === '#') { |
| 260 | + const isHex = entity[1] === 'x' || entity[1] === 'X'; |
| 261 | + const code = isHex ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10); |
| 262 | + |
| 263 | + return Number.isFinite(code) ? String.fromCodePoint(code) : match; |
| 264 | + } |
| 265 | + |
| 266 | + return NAMED_ENTITIES[entity.toLowerCase()] ?? match; |
| 267 | + }); |
| 268 | +} |
0 commit comments