Files
PAGIVA/src/lib/ai/website.ts
T
Loma Bot Ops 5f8f0c9159 Add website link to page profile so the AI can read the shop site
Adds PageProfile.website (with migration). Codex runs without network, so
the profile draft route fetches the site server-side (public hosts only,
redirect-checked, size-capped, cached) and passes its text as
<shop_website>. Other prompts receive the URL via the shop profile.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 21:20:35 +07:00

102 lines
4.7 KiB
TypeScript

import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
const cache = new Map<string, { expiresAt: number; value: string }>();
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(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;|&apos;/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 a shop's public website into short plain text (title, description, visible copy). Empty string if it cannot be read. */
export async function websitePrompt(website: string): Promise<string> {
const cached = cache.get(website);
if (cached && cached.expiresAt > Date.now()) return cached.value;
let value = "";
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 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 = `<shop_website url="${website}">\nTitle: ${title}\nDescription: ${description}\n\n${body}\n</shop_website>`;
}
}
} catch {
value = "";
}
cache.set(website, { expiresAt: Date.now() + 60 * 60_000, value });
return value;
}