114 lines
5.4 KiB
TypeScript
114 lines
5.4 KiB
TypeScript
import { lookup } from "node:dns/promises";
|
|
import { isIP } from "node:net";
|
|
|
|
type WebsiteResearch = { prompt: string; imageUrl: string | null };
|
|
const cache = new Map<string, { expiresAt: number; value: WebsiteResearch }>();
|
|
const MAX_BYTES = 1_500_000;
|
|
const MAX_TEXT = 6_000;
|
|
const MAX_REDIRECTS = 3;
|
|
|
|
/** True for loopback, private, link-local, CGNAT and other non-public addresses (IPv4 and IPv6). */
|
|
function isPrivateAddress(address: string): boolean {
|
|
const mapped = address.toLowerCase().replace(/^::ffff:/, "");
|
|
if (isIP(mapped) === 4) {
|
|
const [a, b] = mapped.split(".").map(Number);
|
|
return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19));
|
|
}
|
|
const v6 = mapped;
|
|
return v6 === "::" || v6 === "::1" || v6.startsWith("fc") || v6.startsWith("fd") || /^fe[89ab]/.test(v6) || v6.startsWith("ff");
|
|
}
|
|
|
|
async function assertPublicHost(url: URL) {
|
|
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("scheme");
|
|
if (url.username || url.password) throw new Error("credentials");
|
|
if (url.port && url.port !== "80" && url.port !== "443") throw new Error("port");
|
|
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) throw new Error("host");
|
|
const addresses = isIP(host) ? [{ address: host }] : await lookup(host, { all: true });
|
|
if (!addresses.length || addresses.some((a) => isPrivateAddress(a.address))) throw new Error("private");
|
|
}
|
|
|
|
function decodeEntities(text: string): string {
|
|
return text
|
|
.replace(/ /gi, " ").replace(/&/gi, "&").replace(/</gi, "<").replace(/>/gi, ">").replace(/"/gi, '"').replace(/'|'/gi, "'")
|
|
.replace(/&#(\d+);/g, (_, n: string) => String.fromCodePoint(Math.min(Number(n), 0x10ffff)));
|
|
}
|
|
|
|
function metaContent(html: string, name: string): string {
|
|
const tag = html.match(new RegExp(`<meta[^>]+(?:name|property)=["']${name}["'][^>]*>`, "i"))?.[0];
|
|
return decodeEntities(tag?.match(/content=["']([^"']*)["']/i)?.[1] ?? "").trim();
|
|
}
|
|
|
|
/** Reads public page text and its declared social-preview image with SSRF protection. */
|
|
export async function websiteResearch(website: string): Promise<WebsiteResearch> {
|
|
const cached = cache.get(website);
|
|
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
let value: WebsiteResearch = { prompt: "", imageUrl: null };
|
|
try {
|
|
let url = new URL(website);
|
|
let response: Response | null = null;
|
|
// Follow redirects by hand so every hop is checked against the same public-host rule.
|
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
await assertPublicHost(url);
|
|
response = await fetch(url, {
|
|
redirect: "manual",
|
|
cache: "no-store",
|
|
signal: AbortSignal.timeout(10_000),
|
|
headers: { accept: "text/html,application/xhtml+xml", "user-agent": "Mozilla/5.0 (compatible; PageManagerBot/1.0)" },
|
|
});
|
|
const location = response.headers.get("location");
|
|
if (response.status >= 300 && response.status < 400 && location) {
|
|
url = new URL(location, url);
|
|
response = null;
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
if (response?.ok && response.body && /text\/html|application\/xhtml/i.test(response.headers.get("content-type") ?? "")) {
|
|
const chunks: Uint8Array[] = [];
|
|
let size = 0;
|
|
const reader = response.body.getReader();
|
|
while (size < MAX_BYTES) {
|
|
const { done, value: chunk } = await reader.read();
|
|
if (done) break;
|
|
chunks.push(chunk);
|
|
size += chunk.length;
|
|
}
|
|
await reader.cancel().catch(() => {});
|
|
const html = Buffer.concat(chunks).toString("utf8");
|
|
const title = decodeEntities(html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] ?? "").replace(/\s+/g, " ").trim();
|
|
const description = metaContent(html, "description") || metaContent(html, "og:description");
|
|
const rawImage = metaContent(html, "og:image") || metaContent(html, "twitter:image");
|
|
let imageUrl: string | null = null;
|
|
try {
|
|
const image = new URL(rawImage, url);
|
|
if (image.protocol === "https:" || image.protocol === "http:") imageUrl = image.toString();
|
|
} catch { /* A page image is optional. */ }
|
|
const body = decodeEntities(
|
|
html
|
|
.replace(/<(script|style|noscript|svg|template|iframe)[\s\S]*?<\/\1>/gi, " ")
|
|
.replace(/<!--[\s\S]*?-->/g, " ")
|
|
.replace(/<\/(p|div|li|h[1-6]|section|article|tr|br)>|<br\s*\/?>/gi, "\n")
|
|
.replace(/<[^>]+>/g, " "),
|
|
)
|
|
.split("\n")
|
|
.map((line) => line.replace(/\s+/g, " ").trim())
|
|
.filter((line) => line.length > 1)
|
|
.join("\n")
|
|
.slice(0, MAX_TEXT);
|
|
if (title || description || body) {
|
|
value = { prompt: `<shop_website url="${website}">\nTitle: ${title}\nDescription: ${description}\n\n${body}\n</shop_website>`, imageUrl };
|
|
}
|
|
}
|
|
} catch {
|
|
value = { prompt: "", imageUrl: null };
|
|
}
|
|
cache.set(website, { expiresAt: Date.now() + 60 * 60_000, value });
|
|
return value;
|
|
}
|
|
|
|
/** Backward-compatible text-only helper for shop profile research. */
|
|
export async function websitePrompt(website: string): Promise<string> {
|
|
return (await websiteResearch(website)).prompt;
|
|
}
|